64
64
Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`
65
65
into the form's constructor; this is how file data gets bound into a form.
67
Handling uploaded files
68
-----------------------
70
.. class:: UploadedFile
72
The final piece of the puzzle is handling the actual file data from
73
:attr:`request.FILES <django.http.HttpRequest.FILES>`. Each entry in this
74
dictionary is an ``UploadedFile`` object -- a simple wrapper around an uploaded
75
file. You'll usually use one of these methods to access the uploaded content:
79
Read the entire uploaded data from the file. Be careful with this
80
method: if the uploaded file is huge it can overwhelm your system if you
81
try to read it into memory. You'll probably want to use ``chunks()``
84
.. method:: multiple_chunks()
86
Returns ``True`` if the uploaded file is big enough to require
87
reading in multiple chunks. By default this will be any file
88
larger than 2.5 megabytes, but that's configurable; see below.
92
A generator returning chunks of the file. If ``multiple_chunks()`` is
93
``True``, you should use this method in a loop instead of ``read()``.
95
In practice, it's often easiest simply to use ``chunks()`` all the time;
96
see the example below.
100
The name of the uploaded file (e.g. ``my_file.txt``).
104
The size, in bytes, of the uploaded file.
106
There are a few other methods and attributes available on ``UploadedFile``
107
objects; see `UploadedFile objects`_ for a complete reference.
109
Putting it all together, here's a common way you might handle an uploaded file::
67
Here's a common way you might handle an uploaded file::
111
69
def handle_uploaded_file(f):
112
70
with open('some/file/name.txt', 'wb+') as destination:
116
74
Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
117
75
large files don't overwhelm your system's memory.
119
Where uploaded data is stored
120
-----------------------------
122
Before you save uploaded files, the data needs to be stored somewhere.
124
By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
125
the entire contents of the upload in memory. This means that saving the file
126
involves only a read from memory and a write to disk and thus is very fast.
128
However, if an uploaded file is too large, Django will write the uploaded file
129
to a temporary file stored in your system's temporary directory. On a Unix-like
130
platform this means you can expect Django to generate a file called something
131
like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
132
file grow in size as Django streams the data onto disk.
134
These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are simply "reasonable
135
defaults". Read on for details on how you can customize or completely replace
138
Changing upload handler behavior
139
--------------------------------
141
Three settings control Django's file upload behavior:
143
:setting:`FILE_UPLOAD_MAX_MEMORY_SIZE`
144
The maximum size, in bytes, for files that will be uploaded into memory.
145
Files larger than :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be
148
Defaults to 2.5 megabytes.
150
:setting:`FILE_UPLOAD_TEMP_DIR`
151
The directory where uploaded files larger than
152
:setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be stored.
154
Defaults to your system's standard temporary directory (i.e. ``/tmp`` on
155
most Unix-like systems).
157
:setting:`FILE_UPLOAD_PERMISSIONS`
158
The numeric mode (i.e. ``0o644``) to set newly uploaded files to. For
159
more information about what these modes mean, see the documentation for
162
If this isn't given or is ``None``, you'll get operating-system
163
dependent behavior. On most platforms, temporary files will have a mode
164
of ``0o600``, and files saved from memory will be saved using the
165
system's standard umask.
167
For security reasons, these permissions aren't applied to the temporary
168
files that are stored in :setting:`FILE_UPLOAD_TEMP_DIR`.
172
If you're not familiar with file modes, please note that the leading
173
``0`` is very important: it indicates an octal number, which is the
174
way that modes must be specified. If you try to use ``644``, you'll
175
get totally incorrect behavior.
177
**Always prefix the mode with a 0.**
179
:setting:`FILE_UPLOAD_HANDLERS`
180
The actual handlers for uploaded files. Changing this setting allows
181
complete customization -- even replacement -- of Django's upload
182
process. See `upload handlers`_, below, for details.
186
("django.core.files.uploadhandler.MemoryFileUploadHandler",
187
"django.core.files.uploadhandler.TemporaryFileUploadHandler",)
189
Which means "try to upload to memory first, then fall back to temporary
77
There are a few other methods and attributes available on ``UploadedFile``
78
objects; see :class:`UploadedFile` for a complete reference.
192
80
Handling uploaded files with a model
193
81
------------------------------------
234
122
form = UploadFileForm()
235
123
return render(request, 'upload.html', {'form': form})
238
``UploadedFile`` objects
239
========================
241
In addition to those inherited from :class:`~django.core.files.File`, all
242
``UploadedFile`` objects define the following methods/attributes:
244
.. attribute:: UploadedFile.content_type
246
The content-type header uploaded with the file (e.g. :mimetype:`text/plain`
247
or :mimetype:`application/pdf`). Like any data supplied by the user, you
248
shouldn't trust that the uploaded file is actually this type. You'll still
249
need to validate that the file contains the content that the content-type
250
header claims -- "trust but verify."
252
.. attribute:: UploadedFile.charset
254
For :mimetype:`text/*` content-types, the character set (i.e. ``utf8``)
255
supplied by the browser. Again, "trust but verify" is the best policy here.
257
.. attribute:: UploadedFile.temporary_file_path()
259
Only files uploaded onto disk will have this method; it returns the full
260
path to the temporary uploaded file.
264
Like regular Python files, you can read the file line-by-line simply by
265
iterating over the uploaded file:
267
.. code-block:: python
269
for line in uploadedfile:
270
do_something_with(line)
272
However, *unlike* standard Python files, :class:`UploadedFile` only
273
understands ``\n`` (also known as "Unix-style") line endings. If you know
274
that you need to handle uploaded files with different line endings, you'll
275
need to do so in your view.
128
.. currentmodule:: django.core.files.uploadhandler
280
130
When a user uploads a file, Django passes off the file data to an *upload
281
131
handler* -- a small class that handles file data as it gets uploaded. Upload
282
132
handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
285
135
("django.core.files.uploadhandler.MemoryFileUploadHandler",
286
136
"django.core.files.uploadhandler.TemporaryFileUploadHandler",)
288
Together the ``MemoryFileUploadHandler`` and ``TemporaryFileUploadHandler``
289
provide Django's default file upload behavior of reading small files into memory
290
and large ones onto disk.
138
Together :class:`MemoryFileUploadHandler` and
139
:class:`TemporaryFileUploadHandler` provide Django's default file upload
140
behavior of reading small files into memory and large ones onto disk.
292
142
You can write custom handlers that customize how Django handles files. You
293
143
could, for example, use custom handlers to enforce user-level quotas, compress
294
144
data on the fly, render progress bars, and even send data to another storage
295
location directly without storing it locally.
145
location directly without storing it locally. See :ref:`custom_upload_handlers`
146
for details on how you can customize or completely replace upload behavior.
297
148
.. _modifying_upload_handlers_on_the_fly:
150
Where uploaded data is stored
151
-----------------------------
153
Before you save uploaded files, the data needs to be stored somewhere.
155
By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
156
the entire contents of the upload in memory. This means that saving the file
157
involves only a read from memory and a write to disk and thus is very fast.
159
However, if an uploaded file is too large, Django will write the uploaded file
160
to a temporary file stored in your system's temporary directory. On a Unix-like
161
platform this means you can expect Django to generate a file called something
162
like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
163
file grow in size as Django streams the data onto disk.
165
These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are simply "reasonable
166
defaults" which can be customized as described in the next section.
168
Changing upload handler behavior
169
--------------------------------
171
There are a few settings which control Django's file upload behavior. See
172
:ref:`File Upload Settings <file-upload-settings>` for details.
299
174
Modifying upload handlers on the fly
300
175
------------------------------------
355
230
def _upload_file_view(request):
356
231
... # Process request
359
Writing custom upload handlers
360
------------------------------
362
All file upload handlers should be subclasses of
363
``django.core.files.uploadhandler.FileUploadHandler``. You can define upload
364
handlers wherever you wish.
369
Custom file upload handlers **must** define the following methods:
371
``FileUploadHandler.receive_data_chunk(raw_data, start)``
372
Receives a "chunk" of data from the file upload.
374
``raw_data`` is a byte string containing the uploaded data.
376
``start`` is the position in the file where this ``raw_data`` chunk
379
The data you return will get fed into the subsequent upload handlers'
380
``receive_data_chunk`` methods. In this way, one handler can be a
381
"filter" for other handlers.
383
Return ``None`` from ``receive_data_chunk`` to short-circuit remaining
384
upload handlers from getting this chunk. This is useful if you're
385
storing the uploaded data yourself and don't want future handlers to
386
store a copy of the data.
388
If you raise a ``StopUpload`` or a ``SkipFile`` exception, the upload
389
will abort or the file will be completely skipped.
391
``FileUploadHandler.file_complete(file_size)``
392
Called when a file has finished uploading.
394
The handler should return an ``UploadedFile`` object that will be stored
395
in ``request.FILES``. Handlers may also return ``None`` to indicate that
396
the ``UploadedFile`` object should come from subsequent upload handlers.
401
Custom upload handlers may also define any of the following optional methods or
404
``FileUploadHandler.chunk_size``
405
Size, in bytes, of the "chunks" Django should store into memory and feed
406
into the handler. That is, this attribute controls the size of chunks
407
fed into ``FileUploadHandler.receive_data_chunk``.
409
For maximum performance the chunk sizes should be divisible by ``4`` and
410
should not exceed 2 GB (2\ :sup:`31` bytes) in size. When there are
411
multiple chunk sizes provided by multiple handlers, Django will use the
412
smallest chunk size defined by any handler.
414
The default is 64*2\ :sup:`10` bytes, or 64 KB.
416
``FileUploadHandler.new_file(field_name, file_name, content_type, content_length, charset)``
417
Callback signaling that a new file upload is starting. This is called
418
before any data has been fed to any upload handlers.
420
``field_name`` is a string name of the file ``<input>`` field.
422
``file_name`` is the unicode filename that was provided by the browser.
424
``content_type`` is the MIME type provided by the browser -- E.g.
427
``content_length`` is the length of the image given by the browser.
428
Sometimes this won't be provided and will be ``None``.
430
``charset`` is the character set (i.e. ``utf8``) given by the browser.
431
Like ``content_length``, this sometimes won't be provided.
433
This method may raise a ``StopFutureHandlers`` exception to prevent
434
future handlers from handling this file.
436
``FileUploadHandler.upload_complete()``
437
Callback signaling that the entire upload (all files) has completed.
439
``FileUploadHandler.handle_raw_input(input_data, META, content_length, boundary, encoding)``
440
Allows the handler to completely override the parsing of the raw
443
``input_data`` is a file-like object that supports ``read()``-ing.
445
``META`` is the same object as ``request.META``.
447
``content_length`` is the length of the data in ``input_data``. Don't
448
read more than ``content_length`` bytes from ``input_data``.
450
``boundary`` is the MIME boundary for this request.
452
``encoding`` is the encoding of the request.
454
Return ``None`` if you want upload handling to continue, or a tuple of
455
``(POST, FILES)`` if you want to return the new data structures suitable
456
for the request directly.