Fixed #8234: Corrected typo in docs/cache.txt
[django.git] / docs / upload_handling.txt
blob488778a4e448d2be32ca30ca7e76ff4cbdcddb47
1 ============
2 File Uploads
3 ============
5 **New in Django development version**
7 Most Web sites wouldn't be complete without a way to upload files. When Django
8 handles a file upload, the file data ends up placed in ``request.FILES`` (for
9 more on the ``request`` object see the documentation for `request and response
10 objects`_). This document explains how files are stored on disk and in memory,
11 and how to customize the default behavior.
13 .. _request and response objects: ../request_response/#attributes
15 Basic file uploads
16 ==================
18 Consider a simple form containing a ``FileField``::
20     from django import forms
22     class UploadFileForm(forms.Form):
23         title = forms.CharField(max_length=50)
24         file  = forms.FileField()
26 A view handling this form will receive the file data in ``request.FILES``, which
27 is a dictionary containing a key for each ``FileField`` (or ``ImageField``, or
28 other ``FileField`` subclass) in the form. So the data from the above form would
29 be accessible as ``request.FILES['file']``.
31 Most of the time, you'll simply pass the file data from ``request`` into the
32 form as described in `binding uploaded files to a form`_. This would look
33 something like::
35     from django.http import HttpResponseRedirect
36     from django.shortcuts import render_to_response
38     # Imaginary function to handle an uploaded file.
39     from somewhere import handle_uploaded_file
41     def upload_file(request):
42         if request.method == 'POST':
43             form = UploadFileForm(request.POST, request.FILES)
44             if form.is_valid():
45                 handle_uploaded_file(request.FILES['file'])
46                 return HttpResponseRedirect('/success/url/')
47         else:
48             form = UploadFileForm()
49         return render_to_response('upload.html', {'form': form})
51 .. _binding uploaded files to a form: ../forms/#binding-uploaded-files-to-a- form
53 Notice that we have to pass ``request.FILES`` into the form's constructor; this
54 is how file data gets bound into a form.
56 Handling uploaded files
57 -----------------------
59 The final piece of the puzzle is handling the actual file data from
60 ``request.FILES``. Each entry in this dictionary is an ``UploadedFile`` object
61 -- a simple wrapper around an uploaded file. You'll usually use one of these
62 methods to access the uploaded content:
64     ``UploadedFile.read()``
65         Read the entire uploaded data from the file. Be careful with this
66         method: if the uploaded file is huge it can overwhelm your system if you
67         try to read it into memory. You'll probably want to use ``chunks()``
68         instead; see below.
70     ``UploadedFile.multiple_chunks()``
71         Returns ``True`` if the uploaded file is big enough to require
72         reading in multiple chunks. By default this will be any file
73         larger than 2.5 megabytes, but that's configurable; see below.
75     ``UploadedFile.chunks()``
76         A generator returning chunks of the file. If ``multiple_chunks()`` is
77         ``True``, you should use this method in a loop instead of ``read()``.
79         In practice, it's often easiest simply to use ``chunks()`` all the time;
80         see the example below.
82     ``UploadedFile.name``
83         The name of the uploaded file (e.g. ``my_file.txt``).
85     ``UploadedFile.size``
86         The size, in bytes, of the uploaded file.
88 There are a few other methods and attributes available on ``UploadedFile``
89 objects; see `UploadedFile objects`_ for a complete reference.
91 Putting it all together, here's a common way you might handle an uploaded file::
93     def handle_uploaded_file(f):
94         destination = open('some/file/name.txt', 'wb+')
95         for chunk in f.chunks():
96             destination.write(chunk)
98 Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
99 large files don't overwhelm your system's memory.
101 Where uploaded data is stored
102 -----------------------------
104 Before you save uploaded files, the data needs to be stored somewhere.
106 By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
107 the entire contents of the upload in memory. This means that saving the file
108 involves only a read from memory and a write to disk and thus is very fast.
110 However, if an uploaded file is too large, Django will write the uploaded file
111 to a temporary file stored in your system's temporary directory. On a Unix-like
112 platform this means you can expect Django to generate a file called something
113 like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
114 file grow in size as Django streams the data onto disk.
116 These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are simply "reasonable
117 defaults". Read on for details on how you can customize or completely replace
118 upload behavior.
120 Changing upload handler behavior
121 --------------------------------
123 Three `settings`_ control Django's file upload behavior:
125     ``FILE_UPLOAD_MAX_MEMORY_SIZE``
126         The maximum size, in bytes, for files that will be uploaded
127         into memory. Files larger than ``FILE_UPLOAD_MAX_MEMORY_SIZE``
128         will be streamed to disk.
130         Defaults to 2.5 megabytes.
132     ``FILE_UPLOAD_TEMP_DIR``
133         The directory where uploaded files larger than ``FILE_UPLOAD_TEMP_DIR``
134         will be stored.
136         Defaults to your system's standard temporary directory (i.e. ``/tmp`` on
137         most Unix-like systems).
139     ``FILE_UPLOAD_HANDLERS``
140         The actual handlers for uploaded files. Changing this setting
141         allows complete customization -- even replacement -- of
142         Django's upload process. See `upload handlers`_, below,
143         for details.
145         Defaults to::
147             ("django.core.files.uploadhandler.MemoryFileUploadHandler",
148              "django.core.files.uploadhandler.TemporaryFileUploadHandler",)
150         Which means "try to upload to memory first, then fall back to temporary
151         files."
153 .. _settings: ../settings/
155 ``UploadedFile`` objects
156 ========================
158 In addition to those inherited from `File`_, all ``UploadedFile`` objects define
159 the following methods/attributes:
161     ``UploadedFile.content_type``
162         The content-type header uploaded with the file (e.g. ``text/plain`` or
163         ``application/pdf``). Like any data supplied by the user, you shouldn't
164         trust that the uploaded file is actually this type. You'll still need to
165         validate that the file contains the content that the content-type header
166         claims -- "trust but verify."
168     ``UploadedFile.charset``
169         For ``text/*`` content-types, the character set (i.e. ``utf8``) supplied
170         by the browser. Again, "trust but verify" is the best policy here.
172     ``UploadedFile.temporary_file_path()``
173         Only files uploaded onto disk will have this method; it returns the full
174         path to the temporary uploaded file.
176 .. _File: ../files/
178 Upload Handlers
179 ===============
181 When a user uploads a file, Django passes off the file data to an *upload
182 handler* -- a small class that handles file data as it gets uploaded. Upload
183 handlers are initially defined in the ``FILE_UPLOAD_HANDLERS`` setting, which
184 defaults to::
186     ("django.core.files.uploadhandler.MemoryFileUploadHandler",
187      "django.core.files.uploadhandler.TemporaryFileUploadHandler",)
189 Together the ``MemoryFileUploadHandler`` and ``TemporaryFileUploadHandler``
190 provide Django's default file upload behavior of reading small files into memory
191 and large ones onto disk.
193 You can write custom handlers that customize how Django handles files. You
194 could, for example, use custom handlers to enforce user-level quotas, compress
195 data on the fly, render progress bars, and even send data to another storage
196 location directly without storing it locally.
198 Modifying upload handlers on the fly
199 ------------------------------------
201 Sometimes particular views require different upload behavior. In these cases,
202 you can override upload handlers on a per-request basis by modifying
203 ``request.upload_handlers``. By default, this list will contain the upload
204 handlers given by ``FILE_UPLOAD_HANDLERS``, but you can modify the list as you
205 would any other list.
207 For instance, suppose you've written a ``ProgressBarUploadHandler`` that
208 provides feedback on upload progress to some sort of AJAX widget. You'd add this
209 handler to your upload handers like this::
211     request.upload_handlers.insert(0, ProgressBarUploadHandler())
213 You'd probably want to use ``list.insert()`` in this case (instead of
214 ``append()``) because a progress bar handler would need to run *before* any
215 other handlers. Remember, the upload handlers are processed in order.
217 If you want to replace the upload handlers completely, you can just assign a new
218 list::
220    request.upload_handlers = [ProgressBarUploadHandler()]
222 .. note::
224     You can only modify upload handlers *before* accessing ``request.FILES`` --
225     it doesn't make sense to change upload handlers after upload handling has
226     already started. If you try to modify ``request.upload_handlers`` after
227     reading from ``request.FILES`` Django will throw an error.
229     Thus, you should always modify uploading handlers as early in your view as
230     possible.
232 Writing custom upload handlers
233 ------------------------------
235 All file upload handlers should be subclasses of
236 ``django.core.files.uploadhandler.FileUploadHandler``. You can define upload
237 handlers wherever you wish.
239 Required methods
240 ~~~~~~~~~~~~~~~~
242 Custom file upload handlers **must** define the following methods:
244     ``FileUploadHandler.receive_data_chunk(self, raw_data, start)``
245         Receives a "chunk" of data from the file upload.
247         ``raw_data`` is a byte string containing the uploaded data.
249         ``start`` is the position in the file where this ``raw_data`` chunk
250         begins.
252         The data you return will get fed into the subsequent upload handlers'
253         ``receive_data_chunk`` methods. In this way, one handler can be a
254         "filter" for other handlers.
256         Return ``None`` from ``receive_data_chunk`` to sort-circuit remaining
257         upload handlers from getting this chunk.. This is useful if you're
258         storing the uploaded data yourself and don't want future handlers to
259         store a copy of the data.
261         If you raise a ``StopUpload`` or a ``SkipFile`` exception, the upload
262         will abort or the file will be completely skipped.
264     ``FileUploadHandler.file_complete(self, file_size)``
265         Called when a file has finished uploading.
267         The handler should return an ``UploadedFile`` object that will be stored
268         in ``request.FILES``. Handlers may also return ``None`` to indicate that
269         the ``UploadedFile`` object should come from subsequent upload handlers.
271 Optional methods
272 ~~~~~~~~~~~~~~~~
274 Custom upload handlers may also define any of the following optional methods or
275 attributes:
277     ``FileUploadHandler.chunk_size``
278         Size, in bytes, of the "chunks" Django should store into memory and feed
279         into the handler. That is, this attribute controls the size of chunks
280         fed into ``FileUploadHandler.receive_data_chunk``.
282         For maximum performance the chunk sizes should be divisible by ``4`` and
283         should not exceed 2 GB (2\ :sup:`31` bytes) in size. When there are
284         multiple chunk sizes provided by multiple handlers, Django will use the
285         smallest chunk size defined by any handler.
287         The default is 64*2\ :sup:`10` bytes, or 64 KB.
289     ``FileUploadHandler.new_file(self, field_name, file_name, content_type, content_length, charset)``
290         Callback signaling that a new file upload is starting. This is called
291         before any data has been fed to any upload handlers.
293         ``field_name`` is a string name of the file ``<input>`` field.
295         ``file_name`` is the unicode filename that was provided by the browser.
297         ``content_type`` is the MIME type provided by the browser -- E.g.
298         ``'image/jpeg'``.
300         ``content_length`` is the length of the image given by the browser.
301         Sometimes this won't be provided and will be ``None``., ``None``
302         otherwise.
304         ``charset`` is the character set (i.e. ``utf8``) given by the browser.
305         Like ``content_length``, this sometimes won't be provided.
307         This method may raise a ``StopFutureHandlers`` exception to prevent
308         future handlers from handling this file.
310     ``FileUploadHandler.upload_complete(self)``
311         Callback signaling that the entire upload (all files) has completed.
313     ``FileUploadHandler.handle_raw_input(self, input_data, META, content_length, boundary, encoding)``
314         Allows the handler to completely override the parsing of the raw
315         HTTP input.
317         ``input_data`` is a file-like object that supports ``read()``-ing.
319         ``META`` is the same object as ``request.META``.
321         ``content_length`` is the length of the data in ``input_data``. Don't
322         read more than ``content_length`` bytes from ``input_data``.
324         ``boundary`` is the MIME boundary for this request.
326         ``encoding`` is the encoding of the request.
328         Return ``None`` if you want upload handling to continue, or a tuple of
329         ``(POST, FILES)`` if you want to return the new data structures suitable
330         for the request directly.