Django处理文件上传File Uploads
- HttpRequest.FILES
表单上传的文件对象存储在类字典对象request.FILES中。
file_obj = request.FILES.get('file', None)
print(file_obj.name)
print(file_obj.size)
- UploadedFile
UploadedFile是类文件对象,具有以下方法和属性:
1. UploadedFile.read()
读取整个上传文件的数据,文件较大时慎用。
2. UploadedFile.multiple_chunks(chunk_size=None)
判断文件是否足够大,一般为2.5M
3. UploadedFile.chunks(chunk_size=None)
返回一个生成器对象,当multiple_chunks()为True时应该使用这个方法来代替read().
4. UploadedFile.name
上传文件的name。
5. UploadedFile.size
上传文件的大小。
6. UploadedFile.content_type
上传文件时的content_type报头,例如(e.g. text/plain or application/pdf).
7. UpladedFile.charset
编码
上传方式一:
表单上传:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload_file/" method="post" enctype="multipart/form-data"> # 注意 enctype="multipart/form-data"
<input type="file" name="file"> <input type="submit" value="上传"> </form>
</body>
</html>
后台:
def file_upload(request): if request.method == 'GET': return render(request, 'file_upload.html') elif request.method == 'POST': file_obj = request.FILES.get('file', None) print(file_obj.name) print(file_obj.size) with open('static/images/' + file_obj.name, 'wb') as f: for line in file_obj.chunks(): f.write(line) f.close() return HttpResponse('OK')
上传方式二:
form 类上传:
from类:
class FileForm(forms.Form):
file = fields.FileField()
前段:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload_file/" method="post" enctype="multipart/form-data"> {{ obj.file }} <input type="submit" value="上传"> </form> </body> </html>
后台:
def file_upload(request): if request.method == 'GET': obj = FileForm() return render(request, 'file_upload.html', {'obj': obj}) elif request.method == 'POST': obj = FileForm(request.POST, request.FILES) # 必须填 request.POST if obj.is_valid(): print(obj.cleaned_data) # {'file': <InMemoryUploadedFile: image007.jpg (image/jpeg)>} with open('static/images/' + obj.cleaned_data['file'].name, 'wb') as f: for line in obj.cleaned_data['file'].chunks(): f.write(line) f.close() else: print(obj.errors) return HttpResponse('OK')
上传方式三:
ajax上传:
待续...