Django 文件上传
1、正常方式
# 前端
<form action='/upload.html' method='post' enctype='multipart/form-data'>
{% csrf_token %}
<input type='text' name='user'>
<input type='file' name='img'>
<input type='submit' value='提交'>
</form>
# 修改file的样式 用其它组件放在他上面,并将file透明度设置为0
<div style='position: relative'> # 将div中的内容设置为可绝对定位
<img src='xxx'>
<input type='file' name='img' style='opacity:0; position:sbsolute; top:0; left:0;'>
# 通过样式将img与file再设置为大小相同即可
</div>
# views.py
def upload(request):
if request.method == 'GET':
return render(request, 'upload.html')
elif request.method == 'POST':
user = request.POST.get('user')
img = request.FILES.get('img') # img是一个对象,里面封装了文件名、大小、内容。。。
print(img.name)
pinrt(img.size)
f = open(img.name, 'wb')
for line in img.chunks():
f.write(line)
f.close()
return HttpResponse('...')
2、使用Django Form组件
# 前端 <form action='/upload.html' method='post' enctype='multipart/form-data'> {% csrf_token %} <input type='text' name='user'> <input type='file' name='img'> <input type='submit' value='提交'> </form> # 修改file的样式 用其它组件放在他上面,并将file透明度设置为0 <div style='position: relative'> # 将div中的内容设置为可绝对定位 <img src='xxx'> <input type='file' name='img' style='opacity:0; position:sbsolute; top:0; left:0;'> # 通过样式将img与file再设置为大小相同即可 </div>
# views.py from django import forms
from django.forms import fields
class UploadForm(forms.Form):
user = fields.CharField()
img = fields.FileField()
def upload(request): if request.method == 'GET': return render(request, 'upload.html') elif request.method == 'POST':
obj = UploadForm(request.POST,request.FILES)
if obj.is_valid():
user = obj.cleaned_data['user']
img = obj.cleaned_data['img']
user = request.POST.get('user') img = request.FILES.get('img') # img是一个对象,里面封装了文件名、大小、内容。。。 print(img.name) pinrt(img.size) f = open(img.name, 'wb') for line in img.chunks(): f.write(line) f.close() return HttpResponse('...')