file-uploads.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. ============
  2. File Uploads
  3. ============
  4. .. currentmodule:: django.core.files.uploadedfile
  5. When Django handles a file upload, the file data ends up placed in
  6. :attr:`request.FILES <django.http.HttpRequest.FILES>` (for more on the
  7. ``request`` object see the documentation for :doc:`request and response objects
  8. </ref/request-response>`). This document explains how files are stored on disk
  9. and in memory, and how to customize the default behavior.
  10. .. warning::
  11. There are security risks if you are accepting uploaded content from
  12. untrusted users! See the security guide's topic on
  13. :ref:`user-uploaded-content-security` for mitigation details.
  14. Basic file uploads
  15. ==================
  16. Consider a simple form containing a :class:`~django.forms.FileField`::
  17. # In forms.py...
  18. from django import forms
  19. class UploadFileForm(forms.Form):
  20. title = forms.CharField(max_length=50)
  21. file = forms.FileField()
  22. A view handling this form will receive the file data in
  23. :attr:`request.FILES <django.http.HttpRequest.FILES>`, which is a dictionary
  24. containing a key for each :class:`~django.forms.FileField` (or
  25. :class:`~django.forms.ImageField`, or other :class:`~django.forms.FileField`
  26. subclass) in the form. So the data from the above form would
  27. be accessible as ``request.FILES['file']``.
  28. Note that :attr:`request.FILES <django.http.HttpRequest.FILES>` will only
  29. contain data if the request method was ``POST`` and the ``<form>`` that posted
  30. the request has the attribute ``enctype="multipart/form-data"``. Otherwise,
  31. ``request.FILES`` will be empty.
  32. Most of the time, you'll simply pass the file data from ``request`` into the
  33. form as described in :ref:`binding-uploaded-files`. This would look
  34. something like::
  35. from django.http import HttpResponseRedirect
  36. from django.shortcuts import render
  37. from .forms import UploadFileForm
  38. # Imaginary function to handle an uploaded file.
  39. from somewhere import handle_uploaded_file
  40. def upload_file(request):
  41. if request.method == 'POST':
  42. form = UploadFileForm(request.POST, request.FILES)
  43. if form.is_valid():
  44. handle_uploaded_file(request.FILES['file'])
  45. return HttpResponseRedirect('/success/url/')
  46. else:
  47. form = UploadFileForm()
  48. return render(request, 'upload.html', {'form': form})
  49. Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`
  50. into the form's constructor; this is how file data gets bound into a form.
  51. Here's a common way you might handle an uploaded file::
  52. def handle_uploaded_file(f):
  53. with open('some/file/name.txt', 'wb+') as destination:
  54. for chunk in f.chunks():
  55. destination.write(chunk)
  56. Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
  57. large files don't overwhelm your system's memory.
  58. There are a few other methods and attributes available on ``UploadedFile``
  59. objects; see :class:`UploadedFile` for a complete reference.
  60. Handling uploaded files with a model
  61. ------------------------------------
  62. If you're saving a file on a :class:`~django.db.models.Model` with a
  63. :class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm`
  64. makes this process much easier. The file object will be saved to the location
  65. specified by the :attr:`~django.db.models.FileField.upload_to` argument of the
  66. corresponding :class:`~django.db.models.FileField` when calling
  67. ``form.save()``::
  68. from django.http import HttpResponseRedirect
  69. from django.shortcuts import render
  70. from .forms import ModelFormWithFileField
  71. def upload_file(request):
  72. if request.method == 'POST':
  73. form = ModelFormWithFileField(request.POST, request.FILES)
  74. if form.is_valid():
  75. # file is saved
  76. form.save()
  77. return HttpResponseRedirect('/success/url/')
  78. else:
  79. form = ModelFormWithFileField()
  80. return render(request, 'upload.html', {'form': form})
  81. If you are constructing an object manually, you can simply assign the file
  82. object from :attr:`request.FILES <django.http.HttpRequest.FILES>` to the file
  83. field in the model::
  84. from django.http import HttpResponseRedirect
  85. from django.shortcuts import render
  86. from .forms import UploadFileForm
  87. from .models import ModelWithFileField
  88. def upload_file(request):
  89. if request.method == 'POST':
  90. form = UploadFileForm(request.POST, request.FILES)
  91. if form.is_valid():
  92. instance = ModelWithFileField(file_field=request.FILES['file'])
  93. instance.save()
  94. return HttpResponseRedirect('/success/url/')
  95. else:
  96. form = UploadFileForm()
  97. return render(request, 'upload.html', {'form': form})
  98. Uploading multiple files
  99. ------------------------
  100. If you want to upload multiple files using one form field, set the ``multiple``
  101. HTML attribute of field's widget:
  102. .. snippet::
  103. :filename: forms.py
  104. from django import forms
  105. class FileFieldForm(forms.Form):
  106. file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
  107. Then override the ``post`` method of your
  108. :class:`~django.views.generic.edit.FormView` subclass to handle multiple file
  109. uploads:
  110. .. snippet::
  111. :filename: views.py
  112. from django.views.generic.edit import FormView
  113. from .forms import FileFieldForm
  114. class FileFieldView(FormView):
  115. form_class = FileFieldForm
  116. template_name = 'upload.html' # Replace with your template.
  117. success_url = '...' # Replace with your URL or reverse().
  118. def post(self, request, *args, **kwargs):
  119. form_class = self.get_form_class()
  120. form = self.get_form(form_class)
  121. files = request.FILES.getlist('file_field')
  122. if form.is_valid():
  123. for f in files:
  124. ... # Do something with each file.
  125. return self.form_valid(form)
  126. else:
  127. return self.form_invalid(form)
  128. Upload Handlers
  129. ===============
  130. .. currentmodule:: django.core.files.uploadhandler
  131. When a user uploads a file, Django passes off the file data to an *upload
  132. handler* -- a small class that handles file data as it gets uploaded. Upload
  133. handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
  134. which defaults to::
  135. ["django.core.files.uploadhandler.MemoryFileUploadHandler",
  136. "django.core.files.uploadhandler.TemporaryFileUploadHandler"]
  137. Together :class:`MemoryFileUploadHandler` and
  138. :class:`TemporaryFileUploadHandler` provide Django's default file upload
  139. behavior of reading small files into memory and large ones onto disk.
  140. You can write custom handlers that customize how Django handles files. You
  141. could, for example, use custom handlers to enforce user-level quotas, compress
  142. data on the fly, render progress bars, and even send data to another storage
  143. location directly without storing it locally. See :ref:`custom_upload_handlers`
  144. for details on how you can customize or completely replace upload behavior.
  145. .. _modifying_upload_handlers_on_the_fly:
  146. Where uploaded data is stored
  147. -----------------------------
  148. Before you save uploaded files, the data needs to be stored somewhere.
  149. By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
  150. the entire contents of the upload in memory. This means that saving the file
  151. involves only a read from memory and a write to disk and thus is very fast.
  152. However, if an uploaded file is too large, Django will write the uploaded file
  153. to a temporary file stored in your system's temporary directory. On a Unix-like
  154. platform this means you can expect Django to generate a file called something
  155. like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
  156. file grow in size as Django streams the data onto disk.
  157. These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are simply "reasonable
  158. defaults" which can be customized as described in the next section.
  159. Changing upload handler behavior
  160. --------------------------------
  161. There are a few settings which control Django's file upload behavior. See
  162. :ref:`File Upload Settings <file-upload-settings>` for details.
  163. Modifying upload handlers on the fly
  164. ------------------------------------
  165. Sometimes particular views require different upload behavior. In these cases,
  166. you can override upload handlers on a per-request basis by modifying
  167. ``request.upload_handlers``. By default, this list will contain the upload
  168. handlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list
  169. as you would any other list.
  170. For instance, suppose you've written a ``ProgressBarUploadHandler`` that
  171. provides feedback on upload progress to some sort of AJAX widget. You'd add this
  172. handler to your upload handlers like this::
  173. request.upload_handlers.insert(0, ProgressBarUploadHandler())
  174. You'd probably want to use ``list.insert()`` in this case (instead of
  175. ``append()``) because a progress bar handler would need to run *before* any
  176. other handlers. Remember, the upload handlers are processed in order.
  177. If you want to replace the upload handlers completely, you can just assign a new
  178. list::
  179. request.upload_handlers = [ProgressBarUploadHandler()]
  180. .. note::
  181. You can only modify upload handlers *before* accessing
  182. ``request.POST`` or ``request.FILES`` -- it doesn't make sense to
  183. change upload handlers after upload handling has already
  184. started. If you try to modify ``request.upload_handlers`` after
  185. reading from ``request.POST`` or ``request.FILES`` Django will
  186. throw an error.
  187. Thus, you should always modify uploading handlers as early in your view as
  188. possible.
  189. Also, ``request.POST`` is accessed by
  190. :class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by
  191. default. This means you will need to use
  192. :func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you
  193. to change the upload handlers. You will then need to use
  194. :func:`~django.views.decorators.csrf.csrf_protect` on the function that
  195. actually processes the request. Note that this means that the handlers may
  196. start receiving the file upload before the CSRF checks have been done.
  197. Example code::
  198. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  199. @csrf_exempt
  200. def upload_file_view(request):
  201. request.upload_handlers.insert(0, ProgressBarUploadHandler())
  202. return _upload_file_view(request)
  203. @csrf_protect
  204. def _upload_file_view(request):
  205. ... # Process request