A detailed description of the Django file upload mechanism usage

Source: Internet
Author: User

A detailed description of the Django file upload mechanism usage

Http://www.jbxue.com/article/24283.html

Share the usage of the Django file upload mechanism, including the principle of basically transmitting files, and how to handle uploading files in a way that requires a friend's reference.

When Django handles uploading a file, the file data is placed on request. Files. This document explains how a file is stored on disk or in memory, and how to customize the default behavior.

One, basic file upload
Consider a simple form that contains Filefield:

Copy Code code example:

From Django Import forms
Classuploadfileform (forms. Form):
Title=forms. Charfield (MAX_LENGTH=50)
File=forms. Filefield ()

A view that handles this form will be on request. Files to accept file data, request. Files is a dictionary that contains a key for each filefield (or ImageField, or other subclass of Filefield). So the data from the above form will be available through request. files[' file ' key to access. Note the request. Files only in the request method is post and a POST request is issued <form> has the attribute enctype= "Multipart/form-data". otherwise, request. Files will be empty.

Another simple example:

Copy Code code example:

From Fdjango.http Improt Httpresponseredirect
From django.shortcuts import Render_to_response
From somewhere import handle_uploaded_file
def upload_file (Request):
if Request.method = = ' Post ':
form = Uploadfileform (rquest. Post,request. FILES)
If Form.is_valid ():
Handle_uploaded_file (Request. files[' file '])
Return Httpresponseredirect ('/success/ur/')
Else
form = Uploadfileform ()
Return Render_to_response (' upload.html ', {' form ': Form})

Be aware that the request must be. Files are passed to the form's constructor, which is how the file data is stained with the form.

Second, processing the uploaded files
The final challenge is how to deal with the request. Files in the real file.
Each input to this dictionary is a UploadedFile object-a simple wrapper for an uploaded file.
Typically, the following methods are used to access the uploaded content:
Uploadedfile.read (): reads the entire uploaded data from the file. Be careful with the whole method: If the file is large, you can slow down your system by reading it into memory. You may want to use chunks () instead, see below;
Uploadedfile.multiple_chunks (): If the uploaded file is large enough it needs to be chunked to return to true. The default value is 2.5 trillion, of course, this value is adjustable, look at the following uploadedfile.chunks (): A generator that returns a block of files. If Multiple_chunks () is true, you should use this method in a loop instead of using read ();
Uploadedfile.name: Upload the name of the file (e.g. M_file.txt)
Uploadedfile.size: The size of the uploaded file expressed in bytes.
There are several other methods and properties. You can check it out for yourself.
Put them together, here's a general way you handle uploading files:

Copy Code code example:

Def handle_uploaded_file (f):
Destination = open (' Some/file/name.txt ', ' wb+ ')
For chunk in F.chunks ():
Destination.write (Chunk)
Destination.close ()

Looping over uploadedfile.chunks () rather than using read () ensures that large files do not use your system memory in large quantities.

Third, where does the uploaded data exist?
Before you save the uploaded file, the data needs to be saved in some places. By default, if an uploaded file is less than 2.5 megabytes, Django will put the uploaded item in memory. This means that as long as the data is read from memory and saved to the hard disk, so soon. However, if an uploaded file is too large, Django writes the uploaded file to a temporary file, which is in your temporary file path. On the Unix-like platform means you can foresee that Django produces a file saved as a/tmp/tmpzfp6i6.upload file. If the file is large enough, you can see that the size of the file is increasing.
A lot of details are--2.5m;/tmp, and so on are simple, seemingly reasonable default values. Read on to see how you personalize or completely replace upload behavior.

Four, change the upload processing behavior
Three settings change Django's upload processing behavior:
File_upload_max_memory_size: The maximum size, in bytes, to memory. Files larger than this value will be saved to disk first. Default is 2.5 MB
File_upload_temp_dir: A file larger than File_upload_max_memory_size will be temporarily saved somewhere. The default is the system standard temporary path.
File_upload_permissions: If this is not given or none, you will get a system-independent behavior. Most platforms, temporary files have a 0600 mode, and files saved from memory will use the system standard Umask.
File_upload_handlers: The processor that uploaded the file. Changing this setting allows for full personalization--even in lieu of the--django upload process.
The default is:

("Django.core.files.uploadhandler.MemoryFileUploadHandler",
"Django.core.files.uploadhandler.TemporaryFileUploadHandler",)

UploadedFile Object
Class UploadedFile
As a supplement to those heavy file inheritance, the known UploadedFile object defines the following methods and properties:
Uploadedfile.content_type
The Content_Type header of the file (such as Text/plain
Orapplication/pdf
)。 Like any data provided by a user, you should not trust that the uploaded data is this type. You still have to verify that this file contains the content-type--"Trust but authentication" of this header statement.
Uploadedfile.charset
For text/* Content-types, the browser provides the character set. Again, "Trust but verify" is the best strategy.
Uploadedfile.temporary_file_path (): This method is only available to files that are uploaded to the disk, and it returns the full path of the temporary upload file.
Attention:
Like the usual Python file, you can iterate over the uploaded file to read the file one line at a line:

For line in Uploadedfile:do_something_with (line)

However, unlike standard Python files, the UploadedFile value knows the end of/N (also known as UNIX style). If you know that you need to deal with files with different styles at the end, you will have to deal with them in your view.

Five, upload processing handle:
When a user uploads a file, Django loves that file data passed to the upload processing handle--a small class that processes files as files are uploaded. The upload processing handle is file_upload_handlers initialized by default:

Copy Code code example:

(
"Django.core.files.uploadhandler.MemoryFileUploadHandler"
,
"Django.core.files.uploadhandler.TemporaryFileUploadHandler"

,)

Both provide the default behavior for Django to handle small files and large files. You can personalize the behavior of the Django processing file by personalizing the handle. For example, you can use a personalized handle to enforce user quotas, compress data in real time, render progress bars, and even send data to another store while saving locally.

Six, real-time modification of upload processing handle
Sometimes some views use different upload behaviors. In this case, you can rewrite an upload handle and modify it by Request.upload_handlers. By default, this list contains the processing handles provided by File_upload_handlers, but you can modify the list as you would any other list.
For example, by joining you wrote a call
Progressbaruploadhandler
Handle to the handler. You can add the following form to your upload processing handle:
Request.upload_handlers.insert (0,progressbaruploadhandler ())
You win using List.insert () in this case. Because the progress bar handles the handle, it needs to be executed first. Remember that the handle handles are executed in order.
If you like to completely replace the upload processing handle, you can assign a new list:
Request.upload_handlers=[progressbaruploadhandler ()]
Note: You can only access the request. Modify the upload handle before post or request.files. --If the upload process starts, then it's useless to change it. If you have accessed the request before modifying Reqeust.uplaod_handlers. POST
or request. FILES
, Django throws an error.
So, in your view, modify the upload handling handle as early as possible.

To write a custom upload handling handle:

All upload processing handles should be django.core.files.uploadhandler.FileUploadHandler subclasses. You can define a handle wherever you need it. The method you need:

Custom upload handling handles must be defined by: Fileuploadhandler.receive_data_chunk (Self,raw_data,start): Receives a block from a file.

Raw_data is an already uploaded byte stream start is the position where the Raw_data block starts

The data you return will be passed to the next processing handle in the Receive_data_chunk method. Such a processing handle is another filter.

Returning none will prevent the subsequent processing handle from getting this block, which is useful when you store the data yourself and do not want other handles to store the copy.

If you trigger an stopupload or Skipfile exception, the upload is discarded or the file is completely skipped. Fileuploadhandler.file_complete (self, file_size)

Called when the file upload is complete.

The handle handle should return a UploadFile object that can be stored in the request. Files. Processing handles can also return none to make the UploadFile object come from a later upload handle.

The rest is an optional approach to implementation.

File_upload_max_memory_size = 209715200 File_upload_max_memory_size = 209715200

Before you take a good test of the machine, it is how to use memory, when to start to deposit the temp directory, how to migrate to the upload directory under the

File upload, if an uploaded file is less than 2.5 trillion, Django will upload things in memory, if the uploaded file is larger than 2.5m,django to write the entire uploaded file to a temporary file, this file in the temporary file path. After uploading, the _upload () method in the view will be called to write the temporary files in the temporary folder block to the upload file, the size of each block is 64K, the temporary file will be deleted after writing. Uploadedfile.multiple_chunks (): If the uploaded file is large enough it needs to be chunked to return to true. The default value is 2.5 trillion, of course, this value is adjustable, look at the following uploadedfile.chunks (): A generator that returns a block of files. If Multiple_chunks () is true, you should use this method in a loop instead of using read ();

Before you save the uploaded file, the data needs to be saved in some places. By default, if an uploaded file is less than 2.5 megabytes, Django will put the uploaded item in memory. This means that as long as the data is read from memory and saved to the hard disk, so soon. However, if an uploaded file is too large, Django writes the uploaded file to a temporary file, which is in your temporary file path. On the Unix-like platform means you can foresee that Django produces a file saved as a/tmp/tmpzfp6i6.upload file. If the file is large enough, you can see that the size of the file is increasing.

Three settings change Django's upload processing behavior:

File_upload_max_memory_size: The maximum size, in bytes, to memory. Files larger than this value will be saved to disk first. Default is 2.5 MB
File_upload_temp_dir: A file larger than File_upload_max_memory_size will be temporarily saved somewhere. The default is the system standard temporary path.
File_upload_permissions: If this is not given or none, you will get a system-independent behavior.

Most platforms, temporary files have a 0600 mode, and files saved from memory will use the system standard Umask.

Django File upload mechanism usage explanation (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.