2
0

file-uploads.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 form containing a :class:`~django.forms.FileField`:
  17. .. code-block:: python
  18. :caption: ``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``, at least one file field was
  31. actually posted, and the ``<form>`` that posted the request has the attribute
  32. ``enctype="multipart/form-data"``. Otherwise, ``request.FILES`` will be empty.
  33. Most of the time, you'll pass the file data from ``request`` into the form as
  34. described in :ref:`binding-uploaded-files`. This would look something like:
  35. .. code-block:: python
  36. :caption: ``views.py``
  37. from django.http import HttpResponseRedirect
  38. from django.shortcuts import render
  39. from .forms import UploadFileForm
  40. # Imaginary function to handle an uploaded file.
  41. from somewhere import handle_uploaded_file
  42. def upload_file(request):
  43. if request.method == "POST":
  44. form = UploadFileForm(request.POST, request.FILES)
  45. if form.is_valid():
  46. handle_uploaded_file(request.FILES["file"])
  47. return HttpResponseRedirect("/success/url/")
  48. else:
  49. form = UploadFileForm()
  50. return render(request, "upload.html", {"form": form})
  51. Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`
  52. into the form's constructor; this is how file data gets bound into a form.
  53. Here's a common way you might handle an uploaded file::
  54. def handle_uploaded_file(f):
  55. with open("some/file/name.txt", "wb+") as destination:
  56. for chunk in f.chunks():
  57. destination.write(chunk)
  58. Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
  59. large files don't overwhelm your system's memory.
  60. There are a few other methods and attributes available on ``UploadedFile``
  61. objects; see :class:`UploadedFile` for a complete reference.
  62. Handling uploaded files with a model
  63. ------------------------------------
  64. If you're saving a file on a :class:`~django.db.models.Model` with a
  65. :class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm`
  66. makes this process much easier. The file object will be saved to the location
  67. specified by the :attr:`~django.db.models.FileField.upload_to` argument of the
  68. corresponding :class:`~django.db.models.FileField` when calling
  69. ``form.save()``::
  70. from django.http import HttpResponseRedirect
  71. from django.shortcuts import render
  72. from .forms import ModelFormWithFileField
  73. def upload_file(request):
  74. if request.method == "POST":
  75. form = ModelFormWithFileField(request.POST, request.FILES)
  76. if form.is_valid():
  77. # file is saved
  78. form.save()
  79. return HttpResponseRedirect("/success/url/")
  80. else:
  81. form = ModelFormWithFileField()
  82. return render(request, "upload.html", {"form": form})
  83. If you are constructing an object manually, you can assign the file object from
  84. :attr:`request.FILES <django.http.HttpRequest.FILES>` to the file field in the
  85. model::
  86. from django.http import HttpResponseRedirect
  87. from django.shortcuts import render
  88. from .forms import UploadFileForm
  89. from .models import ModelWithFileField
  90. def upload_file(request):
  91. if request.method == "POST":
  92. form = UploadFileForm(request.POST, request.FILES)
  93. if form.is_valid():
  94. instance = ModelWithFileField(file_field=request.FILES["file"])
  95. instance.save()
  96. return HttpResponseRedirect("/success/url/")
  97. else:
  98. form = UploadFileForm()
  99. return render(request, "upload.html", {"form": form})
  100. If you are constructing an object manually outside of a request, you can assign
  101. a :class:`~django.core.files.File` like object to the
  102. :class:`~django.db.models.FileField`::
  103. from django.core.management.base import BaseCommand
  104. from django.core.files.base import ContentFile
  105. class MyCommand(BaseCommand):
  106. def handle(self, *args, **options):
  107. content_file = ContentFile(b"Hello world!", name="hello-world.txt")
  108. instance = ModelWithFileField(file_field=content_file)
  109. instance.save()
  110. .. _uploading_multiple_files:
  111. Uploading multiple files
  112. ------------------------
  113. ..
  114. Tests in tests.forms_tests.field_tests.test_filefield.MultipleFileFieldTest
  115. should be updated after any changes in the following snippets.
  116. If you want to upload multiple files using one form field, create a subclass
  117. of the field's widget and set its ``allow_multiple_selected`` class attribute
  118. to ``True``.
  119. In order for such files to be all validated by your form (and have the value of
  120. the field include them all), you will also have to subclass ``FileField``. See
  121. below for an example.
  122. .. admonition:: Multiple file field
  123. Django is likely to have a proper multiple file field support at some point
  124. in the future.
  125. .. code-block:: python
  126. :caption: ``forms.py``
  127. from django import forms
  128. class MultipleFileInput(forms.ClearableFileInput):
  129. allow_multiple_selected = True
  130. class MultipleFileField(forms.FileField):
  131. def __init__(self, *args, **kwargs):
  132. kwargs.setdefault("widget", MultipleFileInput())
  133. super().__init__(*args, **kwargs)
  134. def clean(self, data, initial=None):
  135. single_file_clean = super().clean
  136. if isinstance(data, (list, tuple)):
  137. result = [single_file_clean(d, initial) for d in data]
  138. else:
  139. result = [single_file_clean(data, initial)]
  140. return result
  141. class FileFieldForm(forms.Form):
  142. file_field = MultipleFileField()
  143. Then override the ``form_valid()`` method of your
  144. :class:`~django.views.generic.edit.FormView` subclass to handle multiple file
  145. uploads:
  146. .. code-block:: python
  147. :caption: ``views.py``
  148. from django.views.generic.edit import FormView
  149. from .forms import FileFieldForm
  150. class FileFieldFormView(FormView):
  151. form_class = FileFieldForm
  152. template_name = "upload.html" # Replace with your template.
  153. success_url = "..." # Replace with your URL or reverse().
  154. def form_valid(self, form):
  155. files = form.cleaned_data["file_field"]
  156. for f in files:
  157. ... # Do something with each file.
  158. return super().form_valid(form)
  159. .. warning::
  160. This will allow you to handle multiple files at the form level only. Be
  161. aware that you cannot use it to put multiple files on a single model
  162. instance (in a single field), for example, even if the custom widget is used
  163. with a form field related to a model ``FileField``.
  164. Upload Handlers
  165. ===============
  166. .. currentmodule:: django.core.files.uploadhandler
  167. When a user uploads a file, Django passes off the file data to an *upload
  168. handler* -- a small class that handles file data as it gets uploaded. Upload
  169. handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
  170. which defaults to::
  171. [
  172. "django.core.files.uploadhandler.MemoryFileUploadHandler",
  173. "django.core.files.uploadhandler.TemporaryFileUploadHandler",
  174. ]
  175. Together :class:`MemoryFileUploadHandler` and
  176. :class:`TemporaryFileUploadHandler` provide Django's default file upload
  177. behavior of reading small files into memory and large ones onto disk.
  178. You can write custom handlers that customize how Django handles files. You
  179. could, for example, use custom handlers to enforce user-level quotas, compress
  180. data on the fly, render progress bars, and even send data to another storage
  181. location directly without storing it locally. See :ref:`custom_upload_handlers`
  182. for details on how you can customize or completely replace upload behavior.
  183. Where uploaded data is stored
  184. -----------------------------
  185. Before you save uploaded files, the data needs to be stored somewhere.
  186. By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
  187. the entire contents of the upload in memory. This means that saving the file
  188. involves only a read from memory and a write to disk and thus is very fast.
  189. However, if an uploaded file is too large, Django will write the uploaded file
  190. to a temporary file stored in your system's temporary directory. On a Unix-like
  191. platform this means you can expect Django to generate a file called something
  192. like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
  193. file grow in size as Django streams the data onto disk.
  194. These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are "reasonable defaults"
  195. which can be customized as described in the next section.
  196. Changing upload handler behavior
  197. --------------------------------
  198. There are a few settings which control Django's file upload behavior. See
  199. :ref:`File Upload Settings <file-upload-settings>` for details.
  200. .. _modifying_upload_handlers_on_the_fly:
  201. Modifying upload handlers on the fly
  202. ------------------------------------
  203. Sometimes particular views require different upload behavior. In these cases,
  204. you can override upload handlers on a per-request basis by modifying
  205. ``request.upload_handlers``. By default, this list will contain the upload
  206. handlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list
  207. as you would any other list.
  208. For instance, suppose you've written a ``ProgressBarUploadHandler`` that
  209. provides feedback on upload progress to some sort of AJAX widget. You'd add this
  210. handler to your upload handlers like this::
  211. request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
  212. You'd probably want to use ``list.insert()`` in this case (instead of
  213. ``append()``) because a progress bar handler would need to run *before* any
  214. other handlers. Remember, the upload handlers are processed in order.
  215. If you want to replace the upload handlers completely, you can assign a new
  216. list::
  217. request.upload_handlers = [ProgressBarUploadHandler(request)]
  218. .. note::
  219. You can only modify upload handlers *before* accessing
  220. ``request.POST`` or ``request.FILES`` -- it doesn't make sense to
  221. change upload handlers after upload handling has already
  222. started. If you try to modify ``request.upload_handlers`` after
  223. reading from ``request.POST`` or ``request.FILES`` Django will
  224. throw an error.
  225. Thus, you should always modify uploading handlers as early in your view as
  226. possible.
  227. Also, ``request.POST`` is accessed by
  228. :class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by
  229. default. This means you will need to use
  230. :func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you
  231. to change the upload handlers. You will then need to use
  232. :func:`~django.views.decorators.csrf.csrf_protect` on the function that
  233. actually processes the request. Note that this means that the handlers may
  234. start receiving the file upload before the CSRF checks have been done.
  235. Example code::
  236. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  237. @csrf_exempt
  238. def upload_file_view(request):
  239. request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
  240. return _upload_file_view(request)
  241. @csrf_protect
  242. def _upload_file_view(request):
  243. # Process request
  244. ...
  245. If you are using a class-based view, you will need to use
  246. :func:`~django.views.decorators.csrf.csrf_exempt` on its
  247. :meth:`~django.views.generic.base.View.dispatch` method and
  248. :func:`~django.views.decorators.csrf.csrf_protect` on the method that
  249. actually processes the request. Example code::
  250. from django.utils.decorators import method_decorator
  251. from django.views import View
  252. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  253. @method_decorator(csrf_exempt, name="dispatch")
  254. class UploadFileView(View):
  255. def setup(self, request, *args, **kwargs):
  256. request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
  257. super().setup(request, *args, **kwargs)
  258. @method_decorator(csrf_protect)
  259. def post(self, request, *args, **kwargs):
  260. # Process request
  261. ...