django文件上传

文件上传

前端:

1
2
3
4
5
6
7
8
用这个
<form action="" method="post" enctype="multipart/form-data">
默认是这样
{#<form action="" method="post" enctype="application/x-www-form-urlencoded">#}
<input type="file" name="myfile">
<input type="text" name="password">
<input type="submit" value="提交">
</form>

后台:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def fileupload(request):
if request.method=='GET':
return render(request,'fileupload.html')
if request.method=='POST':
# FILES
print(request.FILES)
print(type(request.FILES.get('myfile')))
# 从字典里根据名字,把文件取出来
myfile=request.FILES.get('myfile')
from django.core.files.uploadedfile import InMemoryUploadedFile
# 文件名字
name=myfile.name
# 打开文件,把上传过来的文件存到本地
with open(name,'wb') as f:
# for line in myfile.chunks():
for line in myfile:
f.write(line)
return HttpResponse('ok')

补充:*****编码方式multipart/form-data或者:application/x-www-form-urlencoded传的数据,都可以从
图灵python大海老师 wechat
python分享公众号
坚持原创技术分享,您的支持将鼓励我继续创作!