django文件上传

views.py

from django.shortcuts import render,HttpResponse
import random
from upload import settings
# Create your views here.

# def upload(request):
#     if request.method == "POST":
#         file_obj = request.FILES.get("upload")
#         print(file_obj.name,)
#         with open(file_obj.name,'wb') as f:
#             for line in file_obj.chunks():
#                 f.write(line)
#                 return HttpResponse("上传成功")
#     return render(request,"upload.html")

def upload(request):
    if request.method == "POST":
        file_obj = request.FILES.get("upload")
        print(file_obj.name)
        # file_name = file_obj.name.rsplit(".",maxsplit=1)[0] + str(random.randint(0,100000))+'.'+file_obj.name.rsplit(".",maxsplit=1)[1]
        # print(file_name)#存在static/media/img文件夹下
        fname = '%s/img/%s' % (settings.MEDIA_ROOT, file_obj.name)
        with open(fname,'wb') as f:
            for line in file_obj.chunks():
                f.write(line)
                return HttpResponse("上传成功")
    return render(request,"upload.html")

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/upload/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <span>文件上传:</span>
    <input type="file" name="upload">
    <input type="submit" value="提交">
</form>


</body>
</html>

setting.py

MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")

存在static/media/img文件夹下

posted @ 2018-08-13 13:56  CHVV  阅读(110)  评论(0)    收藏  举报