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 @   CHVV  阅读(104)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示