uploads.txt 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. ==================================
  2. Uploaded Files and Upload Handlers
  3. ==================================
  4. .. module:: django.core.files.uploadedfile
  5. :synopsis: Classes representing uploaded files.
  6. Uploaded files
  7. ==============
  8. .. class:: UploadedFile
  9. During file uploads, the actual file data is stored in :attr:`request.FILES
  10. <django.http.HttpRequest.FILES>`. Each entry in this dictionary is an
  11. ``UploadedFile`` object (or a subclass) -- a simple wrapper around an uploaded
  12. file. You'll usually use one of these methods to access the uploaded content:
  13. .. method:: UploadedFile.read()
  14. Read the entire uploaded data from the file. Be careful with this method:
  15. if the uploaded file is huge it can overwhelm your system if you try to
  16. read it into memory. You'll probably want to use ``chunks()`` instead; see
  17. below.
  18. .. method:: UploadedFile.multiple_chunks(chunk_size=None)
  19. Returns ``True`` if the uploaded file is big enough to require reading in
  20. multiple chunks. By default this will be any file larger than 2.5 megabytes,
  21. but that's configurable; see below.
  22. .. method:: UploadedFile.chunks(chunk_size=None)
  23. A generator returning chunks of the file. If ``multiple_chunks()`` is
  24. ``True``, you should use this method in a loop instead of ``read()``.
  25. In practice, it's often easiest simply to use ``chunks()`` all the time.
  26. Looping over ``chunks()`` instead of using ``read()`` ensures that large
  27. files don't overwhelm your system's memory.
  28. Here are some useful attributes of ``UploadedFile``:
  29. .. attribute:: UploadedFile.name
  30. The name of the uploaded file (e.g. ``my_file.txt``).
  31. .. attribute:: UploadedFile.size
  32. The size, in bytes, of the uploaded file.
  33. .. attribute:: UploadedFile.content_type
  34. The content-type header uploaded with the file (e.g. :mimetype:`text/plain`
  35. or :mimetype:`application/pdf`). Like any data supplied by the user, you
  36. shouldn't trust that the uploaded file is actually this type. You'll still
  37. need to validate that the file contains the content that the content-type
  38. header claims -- "trust but verify."
  39. .. attribute:: UploadedFile.content_type_extra
  40. .. versionadded:: 1.7
  41. A dictionary containing extra parameters passed to the ``content-type``
  42. header. This is typically provided by services, such as Google App Engine,
  43. that intercept and handle file uploads on your behalf. As a result your
  44. handler may not receive the uploaded file content, but instead a URL or
  45. other pointer to the file. (see `RFC 2388`_ section 5.3).
  46. .. _RFC 2388: http://www.ietf.org/rfc/rfc2388.txt
  47. .. attribute:: UploadedFile.charset
  48. For :mimetype:`text/*` content-types, the character set (i.e. ``utf8``)
  49. supplied by the browser. Again, "trust but verify" is the best policy here.
  50. .. note::
  51. Like regular Python files, you can read the file line-by-line simply by
  52. iterating over the uploaded file:
  53. .. code-block:: python
  54. for line in uploadedfile:
  55. do_something_with(line)
  56. Lines are split using `universal newlines`_. The following are recognized
  57. as ending a line: the Unix end-of-line convention ``'\n'``, the Windows
  58. convention ``'\r\n'``, and the old Macintosh convention ``'\r'``.
  59. .. _universal newlines: http://www.python.org/dev/peps/pep-0278
  60. .. versionchanged:: 1.8
  61. Previously lines were only split on the Unix end-of-line ``'\n'``.
  62. Subclasses of ``UploadedFile`` include:
  63. .. class:: TemporaryUploadedFile
  64. A file uploaded to a temporary location (i.e. stream-to-disk). This class
  65. is used by the
  66. :class:`~django.core.files.uploadhandler.TemporaryFileUploadHandler`. In
  67. addition to the methods from :class:`UploadedFile`, it has one additional
  68. method:
  69. .. method:: TemporaryUploadedFile.temporary_file_path()
  70. Returns the full path to the temporary uploaded file.
  71. .. class:: InMemoryUploadedFile
  72. A file uploaded into memory (i.e. stream-to-memory). This class is used
  73. by the :class:`~django.core.files.uploadhandler.MemoryFileUploadHandler`.
  74. Built-in upload handers
  75. =======================
  76. .. module:: django.core.files.uploadhandler
  77. :synopsis: Django's handlers for file uploads.
  78. Together the :class:`MemoryFileUploadHandler` and
  79. :class:`TemporaryFileUploadHandler` provide Django's default file upload
  80. behavior of reading small files into memory and large ones onto disk. They
  81. are located in ``django.core.files.uploadhandler``.
  82. .. class:: MemoryFileUploadHandler
  83. File upload handler to stream uploads into memory (used for small files).
  84. .. class:: TemporaryFileUploadHandler
  85. Upload handler that streams data into a temporary file using
  86. :class:`~django.core.files.uploadedfile.TemporaryUploadedFile`.
  87. .. _custom_upload_handlers:
  88. Writing custom upload handlers
  89. ==============================
  90. .. class:: FileUploadHandler
  91. All file upload handlers should be subclasses of
  92. ``django.core.files.uploadhandler.FileUploadHandler``. You can define upload
  93. handlers wherever you wish.
  94. Required methods
  95. ~~~~~~~~~~~~~~~~
  96. Custom file upload handlers **must** define the following methods:
  97. .. method:: FileUploadHandler.receive_data_chunk(raw_data, start)
  98. Receives a "chunk" of data from the file upload.
  99. ``raw_data`` is a byte string containing the uploaded data.
  100. ``start`` is the position in the file where this ``raw_data`` chunk
  101. begins.
  102. The data you return will get fed into the subsequent upload handlers'
  103. ``receive_data_chunk`` methods. In this way, one handler can be a
  104. "filter" for other handlers.
  105. Return ``None`` from ``receive_data_chunk`` to short-circuit remaining
  106. upload handlers from getting this chunk. This is useful if you're
  107. storing the uploaded data yourself and don't want future handlers to
  108. store a copy of the data.
  109. If you raise a ``StopUpload`` or a ``SkipFile`` exception, the upload
  110. will abort or the file will be completely skipped.
  111. .. method:: FileUploadHandler.file_complete(file_size)
  112. Called when a file has finished uploading.
  113. The handler should return an ``UploadedFile`` object that will be stored
  114. in ``request.FILES``. Handlers may also return ``None`` to indicate that
  115. the ``UploadedFile`` object should come from subsequent upload handlers.
  116. Optional methods
  117. ~~~~~~~~~~~~~~~~
  118. Custom upload handlers may also define any of the following optional methods or
  119. attributes:
  120. .. attribute:: FileUploadHandler.chunk_size
  121. Size, in bytes, of the "chunks" Django should store into memory and feed
  122. into the handler. That is, this attribute controls the size of chunks
  123. fed into ``FileUploadHandler.receive_data_chunk``.
  124. For maximum performance the chunk sizes should be divisible by ``4`` and
  125. should not exceed 2 GB (2\ :sup:`31` bytes) in size. When there are
  126. multiple chunk sizes provided by multiple handlers, Django will use the
  127. smallest chunk size defined by any handler.
  128. The default is 64*2\ :sup:`10` bytes, or 64 KB.
  129. .. method:: FileUploadHandler.new_file(field_name, file_name, content_type, content_length, charset, content_type_extra)
  130. Callback signaling that a new file upload is starting. This is called
  131. before any data has been fed to any upload handlers.
  132. ``field_name`` is a string name of the file ``<input>`` field.
  133. ``file_name`` is the unicode filename that was provided by the browser.
  134. ``content_type`` is the MIME type provided by the browser -- E.g.
  135. ``'image/jpeg'``.
  136. ``content_length`` is the length of the image given by the browser.
  137. Sometimes this won't be provided and will be ``None``.
  138. ``charset`` is the character set (i.e. ``utf8``) given by the browser.
  139. Like ``content_length``, this sometimes won't be provided.
  140. ``content_type_extra`` is extra information about the file from the
  141. ``content-type`` header. See :attr:`UploadedFile.content_type_extra
  142. <django.core.files.uploadedfile.UploadedFile.content_type_extra>`.
  143. This method may raise a ``StopFutureHandlers`` exception to prevent
  144. future handlers from handling this file.
  145. .. versionadded:: 1.7
  146. The ``content_type_extra`` parameter was added.
  147. .. method:: FileUploadHandler.upload_complete()
  148. Callback signaling that the entire upload (all files) has completed.
  149. .. method:: FileUploadHandler.handle_raw_input(input_data, META, content_length, boundary, encoding)
  150. Allows the handler to completely override the parsing of the raw
  151. HTTP input.
  152. ``input_data`` is a file-like object that supports ``read()``-ing.
  153. ``META`` is the same object as ``request.META``.
  154. ``content_length`` is the length of the data in ``input_data``. Don't
  155. read more than ``content_length`` bytes from ``input_data``.
  156. ``boundary`` is the MIME boundary for this request.
  157. ``encoding`` is the encoding of the request.
  158. Return ``None`` if you want upload handling to continue, or a tuple of
  159. ``(POST, FILES)`` if you want to return the new data structures suitable
  160. for the request directly.