file-uploads.txt 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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_to_response
  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_to_response('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. Upload Handlers
  99. ===============
  100. .. currentmodule:: django.core.files.uploadhandler
  101. When a user uploads a file, Django passes off the file data to an *upload
  102. handler* -- a small class that handles file data as it gets uploaded. Upload
  103. handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
  104. which defaults to::
  105. ["django.core.files.uploadhandler.MemoryFileUploadHandler",
  106. "django.core.files.uploadhandler.TemporaryFileUploadHandler"]
  107. Together :class:`MemoryFileUploadHandler` and
  108. :class:`TemporaryFileUploadHandler` provide Django's default file upload
  109. behavior of reading small files into memory and large ones onto disk.
  110. You can write custom handlers that customize how Django handles files. You
  111. could, for example, use custom handlers to enforce user-level quotas, compress
  112. data on the fly, render progress bars, and even send data to another storage
  113. location directly without storing it locally. See :ref:`custom_upload_handlers`
  114. for details on how you can customize or completely replace upload behavior.
  115. .. _modifying_upload_handlers_on_the_fly:
  116. Where uploaded data is stored
  117. -----------------------------
  118. Before you save uploaded files, the data needs to be stored somewhere.
  119. By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
  120. the entire contents of the upload in memory. This means that saving the file
  121. involves only a read from memory and a write to disk and thus is very fast.
  122. However, if an uploaded file is too large, Django will write the uploaded file
  123. to a temporary file stored in your system's temporary directory. On a Unix-like
  124. platform this means you can expect Django to generate a file called something
  125. like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
  126. file grow in size as Django streams the data onto disk.
  127. These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are simply "reasonable
  128. defaults" which can be customized as described in the next section.
  129. Changing upload handler behavior
  130. --------------------------------
  131. There are a few settings which control Django's file upload behavior. See
  132. :ref:`File Upload Settings <file-upload-settings>` for details.
  133. Modifying upload handlers on the fly
  134. ------------------------------------
  135. Sometimes particular views require different upload behavior. In these cases,
  136. you can override upload handlers on a per-request basis by modifying
  137. ``request.upload_handlers``. By default, this list will contain the upload
  138. handlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list
  139. as you would any other list.
  140. For instance, suppose you've written a ``ProgressBarUploadHandler`` that
  141. provides feedback on upload progress to some sort of AJAX widget. You'd add this
  142. handler to your upload handlers like this::
  143. request.upload_handlers.insert(0, ProgressBarUploadHandler())
  144. You'd probably want to use ``list.insert()`` in this case (instead of
  145. ``append()``) because a progress bar handler would need to run *before* any
  146. other handlers. Remember, the upload handlers are processed in order.
  147. If you want to replace the upload handlers completely, you can just assign a new
  148. list::
  149. request.upload_handlers = [ProgressBarUploadHandler()]
  150. .. note::
  151. You can only modify upload handlers *before* accessing
  152. ``request.POST`` or ``request.FILES`` -- it doesn't make sense to
  153. change upload handlers after upload handling has already
  154. started. If you try to modify ``request.upload_handlers`` after
  155. reading from ``request.POST`` or ``request.FILES`` Django will
  156. throw an error.
  157. Thus, you should always modify uploading handlers as early in your view as
  158. possible.
  159. Also, ``request.POST`` is accessed by
  160. :class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by
  161. default. This means you will need to use
  162. :func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you
  163. to change the upload handlers. You will then need to use
  164. :func:`~django.views.decorators.csrf.csrf_protect` on the function that
  165. actually processes the request. Note that this means that the handlers may
  166. start receiving the file upload before the CSRF checks have been done.
  167. Example code::
  168. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  169. @csrf_exempt
  170. def upload_file_view(request):
  171. request.upload_handlers.insert(0, ProgressBarUploadHandler())
  172. return _upload_file_view(request)
  173. @csrf_protect
  174. def _upload_file_view(request):
  175. ... # Process request