file-uploads.txt 10 KB

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