Debian Codegraph @

docs/topics/http/file-uploads.txt

raw
1 ============
2 File Uploads
3 ============
4
5 .. currentmodule:: django.core.files.uploadedfile
6
7 When Django handles a file upload, the file data ends up placed in
8 :attr:`request.FILES <django.http.HttpRequest.FILES>` (for more on the
9 ``request`` object see the documentation for :doc:`request and response objects
10 </ref/request-response>`). This document explains how files are stored on disk
11 and in memory, and how to customize the default behavior.
12
13 .. warning::
14
15 There are security risks if you are accepting uploaded content from
16 untrusted users! See the security guide's topic on
17 :ref:`user-uploaded-content-security` for mitigation details.
18
19 Basic file uploads
20 ==================
21
22 Consider a form containing a :class:`~django.forms.FileField`:
23
24 .. code-block:: python
25 :caption: ``forms.py``
26
27 from django import forms
28
29
30 class UploadFileForm(forms.Form):
31 title = forms.CharField(max_length=50)
32 file = forms.FileField()
33
34 A view handling this form will receive the file data in
35 :attr:`request.FILES <django.http.HttpRequest.FILES>`, which is a dictionary
36 containing a key for each :class:`~django.forms.FileField` (or
37 :class:`~django.forms.ImageField`, or other :class:`~django.forms.FileField`
38 subclass) in the form. So the data from the above form would
39 be accessible as ``request.FILES['file']``.
40
41 Note that :attr:`request.FILES <django.http.HttpRequest.FILES>` will only
42 contain data if the request method was ``POST``, at least one file field was
43 actually posted, and the ``<form>`` that posted the request has the attribute
44 ``enctype="multipart/form-data"``. Otherwise, ``request.FILES`` will be empty.
45
46 Most of the time, you'll pass the file data from ``request`` into the form as
47 described in :ref:`binding-uploaded-files`. This would look something like:
48
49 .. code-block:: python
50 :caption: ``views.py``
51
52 from django.http import HttpResponseRedirect
53 from django.shortcuts import render
54 from .forms import UploadFileForm
55
56 # Imaginary function to handle an uploaded file.
57 from somewhere import handle_uploaded_file
58
59
60 def upload_file(request):
61 if request.method == "POST":
62 form = UploadFileForm(request.POST, request.FILES)
63 if form.is_valid():
64 handle_uploaded_file(request.FILES["file"])
65 return HttpResponseRedirect("/success/url/")
66 else:
67 form = UploadFileForm()
68 return render(request, "upload.html", {"form": form})
69
70 Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`
71 into the form's constructor; this is how file data gets bound into a form.
72
73 Here's a common way you might handle an uploaded file::
74
75 def handle_uploaded_file(f):
76 with open("some/file/name.txt", "wb+") as destination:
77 for chunk in f.chunks():
78 destination.write(chunk)
79
80 Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
81 large files don't overwhelm your system's memory.
82
83 There are a few other methods and attributes available on ``UploadedFile``
84 objects; see :class:`UploadedFile` for a complete reference.
85
86 Handling uploaded files with a model
87 ------------------------------------
88
89 If you're saving a file on a :class:`~django.db.models.Model` with a
90 :class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm`
91 makes this process much easier. The file object will be saved to the location
92 specified by the :attr:`~django.db.models.FileField.upload_to` argument of the
93 corresponding :class:`~django.db.models.FileField` when calling
94 ``form.save()``::
95
96 from django.http import HttpResponseRedirect
97 from django.shortcuts import render
98 from .forms import ModelFormWithFileField
99
100
101 def upload_file(request):
102 if request.method == "POST":
103 form = ModelFormWithFileField(request.POST, request.FILES)
104 if form.is_valid():
105 # file is saved
106 form.save()
107 return HttpResponseRedirect("/success/url/")
108 else:
109 form = ModelFormWithFileField()
110 return render(request, "upload.html", {"form": form})
111
112 If you are constructing an object manually, you can assign the file object from
113 :attr:`request.FILES <django.http.HttpRequest.FILES>` to the file field in the
114 model::
115
116 from django.http import HttpResponseRedirect
117 from django.shortcuts import render
118 from .forms import UploadFileForm
119 from .models import ModelWithFileField
120
121
122 def upload_file(request):
123 if request.method == "POST":
124 form = UploadFileForm(request.POST, request.FILES)
125 if form.is_valid():
126 instance = ModelWithFileField(file_field=request.FILES["file"])
127 instance.save()
128 return HttpResponseRedirect("/success/url/")
129 else:
130 form = UploadFileForm()
131 return render(request, "upload.html", {"form": form})
132
133 If you are constructing an object manually outside of a request, you can assign
134 a :class:`~django.core.files.File` like object to the
135 :class:`~django.db.models.FileField`::
136
137 from django.core.management.base import BaseCommand
138 from django.core.files.base import ContentFile
139
140
141 class MyCommand(BaseCommand):
142 def handle(self, *args, **options):
143 content_file = ContentFile(b"Hello world!", name="hello-world.txt")
144 instance = ModelWithFileField(file_field=content_file)
145 instance.save()
146
147 .. _uploading_multiple_files:
148
149 Uploading multiple files
150 ------------------------
151
152 ..
153 Tests in tests.forms_tests.field_tests.test_filefield.MultipleFileFieldTest
154 should be updated after any changes in the following snippets.
155
156 If you want to upload multiple files using one form field, create a subclass
157 of the field's widget and set its ``allow_multiple_selected`` class attribute
158 to ``True``.
159
160 In order for such files to be all validated by your form (and have the value of
161 the field include them all), you will also have to subclass ``FileField``. See
162 below for an example.
163
164 .. admonition:: Multiple file field
165
166 Django is likely to have a proper multiple file field support at some point
167 in the future.
168
169 .. code-block:: python
170 :caption: ``forms.py``
171
172 from django import forms
173
174
175 class MultipleFileInput(forms.ClearableFileInput):
176 allow_multiple_selected = True
177
178
179 class MultipleFileField(forms.FileField):
180 def __init__(self, *args, **kwargs):
181 kwargs.setdefault("widget", MultipleFileInput())
182 super().__init__(*args, **kwargs)
183
184 def clean(self, data, initial=None):
185 single_file_clean = super().clean
186 if isinstance(data, (list, tuple)):
187 result = [single_file_clean(d, initial) for d in data]
188 else:
189 result = [single_file_clean(data, initial)]
190 return result
191
192
193 class FileFieldForm(forms.Form):
194 file_field = MultipleFileField()
195
196 Then override the ``form_valid()`` method of your
197 :class:`~django.views.generic.edit.FormView` subclass to handle multiple file
198 uploads:
199
200 .. code-block:: python
201 :caption: ``views.py``
202
203 from django.views.generic.edit import FormView
204 from .forms import FileFieldForm
205
206
207 class FileFieldFormView(FormView):
208 form_class = FileFieldForm
209 template_name = "upload.html" # Replace with your template.
210 success_url = "..." # Replace with your URL or reverse().
211
212 def form_valid(self, form):
213 files = form.cleaned_data["file_field"]
214 for f in files:
215 ... # Do something with each file.
216 return super().form_valid(form)
217
218 .. warning::
219
220 This will allow you to handle multiple files at the form level only. Be
221 aware that you cannot use it to put multiple files on a single model
222 instance (in a single field), for example, even if the custom widget is used
223 with a form field related to a model ``FileField``.
224
225 Upload Handlers
226 ===============
227
228 .. currentmodule:: django.core.files.uploadhandler
229
230 When a user uploads a file, Django passes off the file data to an *upload
231 handler* -- a small class that handles file data as it gets uploaded. Upload
232 handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
233 which defaults to::
234
235 [
236 "django.core.files.uploadhandler.MemoryFileUploadHandler",
237 "django.core.files.uploadhandler.TemporaryFileUploadHandler",
238 ]
239
240 Together :class:`MemoryFileUploadHandler` and
241 :class:`TemporaryFileUploadHandler` provide Django's default file upload
242 behavior of reading small files into memory and large ones onto disk.
243
244 You can write custom handlers that customize how Django handles files. You
245 could, for example, use custom handlers to enforce user-level quotas, compress
246 data on the fly, render progress bars, and even send data to another storage
247 location directly without storing it locally. See :ref:`custom_upload_handlers`
248 for details on how you can customize or completely replace upload behavior.
249
250 Where uploaded data is stored
251 -----------------------------
252
253 Before you save uploaded files, the data needs to be stored somewhere.
254
255 By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
256 the entire contents of the upload in memory. This means that saving the file
257 involves only a read from memory and a write to disk and thus is very fast.
258
259 However, if an uploaded file is too large, Django will write the uploaded file
260 to a temporary file stored in your system's temporary directory. On a Unix-like
261 platform this means you can expect Django to generate a file called something
262 like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
263 file grow in size as Django streams the data onto disk.
264
265 These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are "reasonable defaults"
266 which can be customized as described in the next section.
267
268 Changing upload handler behavior
269 --------------------------------
270
271 There are a few settings which control Django's file upload behavior. See
272 :ref:`File Upload Settings <file-upload-settings>` for details.
273
274 .. _modifying_upload_handlers_on_the_fly:
275
276 Modifying upload handlers on the fly
277 ------------------------------------
278
279 Sometimes particular views require different upload behavior. In these cases,
280 you can override upload handlers on a per-request basis by modifying
281 ``request.upload_handlers``. By default, this list will contain the upload
282 handlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list
283 as you would any other list.
284
285 For instance, suppose you've written a ``ProgressBarUploadHandler`` that
286 provides feedback on upload progress to some sort of AJAX widget. You'd add this
287 handler to your upload handlers like this::
288
289 request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
290
291 Using ``list.insert()``, as shown above, ensures that the progress bar handler
292 is placed at the beginning of the list. Since upload handlers are executed in
293 order, this placement guarantees that the progress bar handler runs before the
294 default handlers, allowing it to track progress across the entire upload.
295
296 If you want to replace the upload handlers completely, you can assign a new
297 list::
298
299 request.upload_handlers = [ProgressBarUploadHandler(request)]
300
301 .. note::
302
303 You can only modify upload handlers *before* accessing
304 ``request.POST`` or ``request.FILES`` -- it doesn't make sense to
305 change upload handlers after upload handling has already
306 started. If you try to modify ``request.upload_handlers`` after
307 reading from ``request.POST`` or ``request.FILES`` Django will
308 throw an error.
309
310 Thus, you should always modify uploading handlers as early in your view as
311 possible.
312
313 Also, ``request.POST`` is accessed by
314 :class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by
315 default. This means you will need to use
316 :func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you
317 to change the upload handlers. You will then need to use
318 :func:`~django.views.decorators.csrf.csrf_protect` on the function that
319 actually processes the request. Note that this means that the handlers may
320 start receiving the file upload before the CSRF checks have been done.
321 Example code::
322
323 from django.views.decorators.csrf import csrf_exempt, csrf_protect
324
325
326 @csrf_exempt
327 def upload_file_view(request):
328 request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
329 return _upload_file_view(request)
330
331
332 @csrf_protect
333 def _upload_file_view(request):
334 # Process request
335 ...
336
337 If you are using a class-based view, you will need to use
338 :func:`~django.views.decorators.csrf.csrf_exempt` on its
339 :meth:`~django.views.generic.base.View.dispatch` method and
340 :func:`~django.views.decorators.csrf.csrf_protect` on the method that
341 actually processes the request. Example code::
342
343 from django.utils.decorators import method_decorator
344 from django.views import View
345 from django.views.decorators.csrf import csrf_exempt, csrf_protect
346
347
348 @method_decorator(csrf_exempt, name="dispatch")
349 class UploadFileView(View):
350 def setup(self, request, *args, **kwargs):
351 request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
352 super().setup(request, *args, **kwargs)
353
354 @method_decorator(csrf_protect)
355 def post(self, request, *args, **kwargs):
356 # Process request
357 ...