关于文件上传
修改myproject/myproject/urls.py
添加路由
# 上传文件 path('upload/list/', upload.upload_list),
新建myproject/app01/views/upload.py
from django.shortcuts import render, HttpResponse def upload_list(request): if request.method == "GET": return render(request, 'upload_list.html') print(request.POST) #请求中的数据 print(request.FILES) #请求发过来的文件 return HttpResponse("...")
新建myproject/app01/templates/upload_list.html
{% extends 'layout.html' %} {% block content %} <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="username"> <input type="file" name="avatar"> <input type="submit" value="提交"> </form> </div> {% endblock %}
注意:
不添加 enctype="multipart/form-data"得到的是<QueryDict: {'csrfmiddlewaretoken': ['OeDA7cKmsOLEneNjULy6Isg0hn6GazDOYkLHPrfHrHOLMuLzNNMRuhENQASgz8o9'], 'username': ['123'], 'avatar': ['20200119123801_bjxpj.jpg']}>文件那返回的是文件名的字符串,并不是文件
添加 enctype="multipart/form-data"得到的是<QueryDict: {'csrfmiddlewaretoken': ['TNDydKrOMZ6Vcn6jdhrEhs34WSR1fMEZ3TLFVZW9LS92BD4z6jFp3hrRv5DBElpk'], 'username': ['222']}><MultiValueDict: {'avatar': [<InMemoryUploadedFile: 20200119123801_bjxpj.jpg (image/jpeg)>]}>
添加后才能得到文件
修改myproject/app01/views/upload.py
from django.shortcuts import render, HttpResponse
def upload_list(request):
if request.method == "GET":
return render(request, 'upload_list.html')
# print(request.POST) #请求中的数据
# print(request.FILES) #请求发过来的文件
# 声明图片的对象
file_object = request.FILES.get("avatar")
# 分块进行存储
# file_object.name 表示图片上传时图片本身是什么名字,保存图片时就用什么名字
f = open(file_object.name, mode='wb')
for chunk in file_object.chunks():
f.write(chunk)
f.close()
return HttpResponse("上传成功")
标签:文件,request,list,upload,myproject,上传 From: https://www.cnblogs.com/kekeeleven/p/17812882.html