服务端:
def upload(req):
if req.method == "GET":
return render(req, 'upload.html')
else:
print(req.POST.get("user"))
img = req.FILES.get('img')
print(type(img))
#(<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>, 获取的是一个对象类型
# print(img.name)
# print(img.size) with open(img.name,"wb") as fp:
for line in img.chunks(): #一块一块获取内容
fp.write(line)
return HttpResponse("....")
前端:
<form action="/upload.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user">
<div style="position: relative">
<p>NB的上传</p>
<input type="file" name="img" style="opacity: 0.2;position: absolute;top:0;left:0;">
</div>
<input type="submit" value="提交"/>
</form>
服务端使用form组件验证:
from django import forms
from django.forms import fields class UploadForm(forms.Form):
user = fields.CharField()
img = fields.FileField() def upload(req):
if req.method == "GET":
return render(req, 'upload.html')
else:
obj = UploadForm(req.POST,req.FILES)
if obj.is_valid():
user = obj.cleaned_data['user']
img = obj.cleaned_data['img']
with open(img.name,"wb") as fp:
for line in img.chunks(): #一块一块获取内容
fp.write(line)
return HttpResponse("....")
return HttpResponse("....")