文件上传

Django处理文件上传时, 文件最终会位于:attr:request.FILES <django.http.HttpRequest.FILES> (想了解更多关于request 对象的信息请阅读 request and response objects 1) 。本文档主要介绍文件是如何存储在硬盘和内存中的,以及如何定制默认行为。

Warning

如果接收不受信任的用户的上传会有安全隐患, 请阅读 :ref:`user-uploaded-content-security`获取详情.

简单文件上传

考虑使用一个简单的表单,表单中包含一个:class:`~django.forms.FileField`字段:

forms.py

  1. from django import forms
  2.  
  3. class UploadFileForm(forms.Form):
  4. title = forms.CharField(max_length=50)
  5. file = forms.FileField()

处理这个表单的视图将通过:attr:request.FILES <django.http.HttpRequest.FILES>获取到文件数据, attr:request.FILES <django.http.HttpRequest.FILES>是包含了表单中每个 :class:~django.forms.FileField (还有 ImageField, 以及其他:class:~django.forms.FileField 的子类)键值的字典 。所以 `数据可以通过`request.FILES['file']``获取到。

请注意只有在请求是通过 POST 提交且提交的 <form> 表单有 enctype="multipart/form-data" 属性的时候,request.FILES 才会包含文件数据,否则的话, request.FILES 是空的。

绝大多数的情况下,你只需要像 binding-uploaded-files中所述将文件数据从``request 传入给 表单,示例如下:

views.py

  1. from django.http import HttpResponseRedirect
  2. from django.shortcuts import render
  3. from .forms import UploadFileForm
  4.  
  5. # Imaginary function to handle an uploaded file.
  6. from somewhere import handle_uploaded_file
  7.  
  8. def upload_file(request):
  9. if request.method == 'POST':
  10. form = UploadFileForm(request.POST, request.FILES)
  11. if form.is_valid():
  12. handle_uploaded_file(request.FILES['file'])
  13. return HttpResponseRedirect('/success/url/')
  14. else:
  15. form = UploadFileForm()
  16. return render(request, 'upload.html', {'form': form})

注意我们必须将 request.FILES 传入到表单的构造方法中,只有这样文件数据才能绑定到表单中。

我们通常可能像这样处理上传文件:

  1. def handle_uploaded_file(f):
  2. with open('some/file/name.txt', 'wb+') as destination:
  3. for chunk in f.chunks():
  4. destination.write(chunk)

使用 UploadedFile.chunks() 而不是 read() 是为了确保即使是大文件又不会将我们系统的内存占满。

There are a few other methods and attributes available on UploadedFileobjects; see UploadedFile for a complete reference.

通过模型来处理上传的文件

If you're saving a file on a Model with aFileField, using a ModelFormmakes this process much easier. The file object will be saved to the locationspecified by the upload_to argument of thecorresponding FileField when callingform.save():

  1. from django.http import HttpResponseRedirect
  2. from django.shortcuts import render
  3. from .forms import ModelFormWithFileField
  4.  
  5. def upload_file(request):
  6. if request.method == 'POST':
  7. form = ModelFormWithFileField(request.POST, request.FILES)
  8. if form.is_valid():
  9. # file is saved
  10. form.save()
  11. return HttpResponseRedirect('/success/url/')
  12. else:
  13. form = ModelFormWithFileField()
  14. return render(request, 'upload.html', {'form': form})

If you are constructing an object manually, you can simply assign the fileobject from request.FILES to the filefield in the model:

  1. from django.http import HttpResponseRedirect
  2. from django.shortcuts import render
  3. from .forms import UploadFileForm
  4. from .models import ModelWithFileField
  5.  
  6. def upload_file(request):
  7. if request.method == 'POST':
  8. form = UploadFileForm(request.POST, request.FILES)
  9. if form.is_valid():
  10. instance = ModelWithFileField(file_field=request.FILES['file'])
  11. instance.save()
  12. return HttpResponseRedirect('/success/url/')
  13. else:
  14. form = UploadFileForm()
  15. return render(request, 'upload.html', {'form': form})

Uploading multiple files

If you want to upload multiple files using one form field, set the multipleHTML attribute of field's widget:

forms.py

  1. from django import forms
  2.  
  3. class FileFieldForm(forms.Form):
  4. file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

Then override the post method of yourFormView subclass to handle multiple fileuploads:

views.py

  1. from django.views.generic.edit import FormView
  2. from .forms import FileFieldForm
  3.  
  4. class FileFieldView(FormView):
  5. form_class = FileFieldForm
  6. template_name = 'upload.html' # Replace with your template.
  7. success_url = '...' # Replace with your URL or reverse().
  8.  
  9. def post(self, request, *args, **kwargs):
  10. form_class = self.get_form_class()
  11. form = self.get_form(form_class)
  12. files = request.FILES.getlist('file_field')
  13. if form.is_valid():
  14. for f in files:
  15. ... # Do something with each file.
  16. return self.form_valid(form)
  17. else:
  18. return self.form_invalid(form)

Upload Handlers

When a user uploads a file, Django passes off the file data to an uploadhandler — a small class that handles file data as it gets uploaded. Uploadhandlers are initially defined in the FILE_UPLOAD_HANDLERS setting,which defaults to:

  1. ["django.core.files.uploadhandler.MemoryFileUploadHandler",
  2. "django.core.files.uploadhandler.TemporaryFileUploadHandler"]

Together MemoryFileUploadHandler andTemporaryFileUploadHandler provide Django's default file uploadbehavior of reading small files into memory and large ones onto disk.

You can write custom handlers that customize how Django handles files. Youcould, for example, use custom handlers to enforce user-level quotas, compressdata on the fly, render progress bars, and even send data to another storagelocation directly without storing it locally. See Writing custom upload handlersfor details on how you can customize or completely replace upload behavior.

Where uploaded data is stored

Before you save uploaded files, the data needs to be stored somewhere.

By default, if an uploaded file is smaller than 2.5 megabytes, Django will holdthe entire contents of the upload in memory. This means that saving the fileinvolves only a read from memory and a write to disk and thus is very fast.

However, if an uploaded file is too large, Django will write the uploaded fileto a temporary file stored in your system's temporary directory. On a Unix-likeplatform this means you can expect Django to generate a file called somethinglike /tmp/tmpzfp6I6.upload. If an upload is large enough, you can watch thisfile grow in size as Django streams the data onto disk.

These specifics — 2.5 megabytes; /tmp; etc. — are simply "reasonabledefaults" which can be customized as described in the next section.

Changing upload handler behavior

There are a few settings which control Django's file upload behavior. SeeFile Upload Settings for details.

Modifying upload handlers on the fly

Sometimes particular views require different upload behavior. In these cases,you can override upload handlers on a per-request basis by modifyingrequest.upload_handlers. By default, this list will contain the uploadhandlers given by FILE_UPLOAD_HANDLERS, but you can modify the listas you would any other list.

For instance, suppose you've written a ProgressBarUploadHandler thatprovides feedback on upload progress to some sort of AJAX widget. You'd add thishandler to your upload handlers like this:

  1. request.upload_handlers.insert(0, ProgressBarUploadHandler(request))

You'd probably want to use list.insert() in this case (instead ofappend()) because a progress bar handler would need to run before anyother handlers. Remember, the upload handlers are processed in order.

If you want to replace the upload handlers completely, you can just assign a newlist:

  1. request.upload_handlers = [ProgressBarUploadHandler(request)]

Note

You can only modify upload handlers before accessingrequest.POST or request.FILES — it doesn't make sense tochange upload handlers after upload handling has alreadystarted. If you try to modify request.upload_handlers afterreading from request.POST or request.FILES Django willthrow an error.

Thus, you should always modify uploading handlers as early in your view aspossible.

Also, request.POST is accessed byCsrfViewMiddleware which is enabled bydefault. This means you will need to usecsrf_exempt() on your view to allow youto change the upload handlers. You will then need to usecsrf_protect() on the function thatactually processes the request. Note that this means that the handlers maystart receiving the file upload before the CSRF checks have been done.Example code:

  1. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  2.  
  3. @csrf_exempt
  4. def upload_file_view(request):
  5. request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
  6. return _upload_file_view(request)
  7.  
  8. @csrf_protect
  9. def _upload_file_view(request):
  10. ... # Process request