Django Upload File
Template HTML (Template File ):
<Form enctype = "multipart/form-Data" method = "Post" Action = "/address/upload/"> <input type = "file" name = "file"/> <br/> <input type = "Submit" value = "Upload File"/> </form>
Like the next form:
from django import formsclass UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField()
The view that processes this form receives the file data in request. Files. Data from the form above can be accessed through request. Files ['file.
Note that only when the request method is post and the <form> attribute enctype = "multipart/form-Data" of the request is sent, the request. files contains file data; otherwise, request. files is empty.
The following view functions:
from django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsefrom somewhere import handle_uploader_filedef upload_file(request): if request.method == ‘POST‘: form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES[‘file‘]) return HttpResponseRedirect(‘/success/url‘) else: form = UploadFileForm() return render_to_response(‘upload.html‘, {‘form‘: form})
You must pass request. files to the form constructor to bind file data to form.
Process uploaded files
Each entry in the dictionary request. Files is an uploadfile object. The uploadfile object has the following methods:
1. uploadfile. Read ():
Read all uploaded data from the file. When the file to be uploaded is too large, the memory may be exhausted and used with caution.
2. uploadfile. multiple_chunks ():
If the size of the uploaded file is large enough to be divided into multiple parts for reading, true is returned. By default, true is returned when the size of the uploaded file is greater than MB. However, this value can be configured.
3. uploadfile. Chunks ():
Returns the multipart Generator for an uploaded file. For example, if multiple_chunks () returns true, chrunks () must be used in the loop instead of read (). You can use chunks () directly.
4. uploadfile. Name (): name of the file to be uploaded
5. uplaodfile. Size (): size of the file to be uploaded (in bytes)
The handle_uploaded_file function can be written in the preceding description.
def handle_uploaded_file(f): destination = open(‘some/file/name.txt‘, ‘wb+‘) for chunk in f.chunks(): destination.write(chunk) destination.close()
Details:
def handle_uploaded_file(f): file_name = "" try: path = "media/editor" + time.strftime(‘/%Y/%m/%d/%H/%M/%S/‘) if not os.path.exists(path): os.makedirs(path) file_name = path + f.name destination = open(file_name, ‘wb+‘) for chunk in f.chunks(): destination.write(chunk) destination.close() except Exception, e: print e return file_name
Storage location of uploaded files
Before saving the uploaded file, the data must be stored in a certain location. By default, when the size of the uploaded file is less than MB, Django will read all the content of the uploaded file into the memory. This means that only one read from memory and one write to disk is saved.
However, when the file to be uploaded is large, Django will write the file to the temporary file and store it in the temporary folder of the system.
Change upload handler Behavior
Three settings control the upload of Django files:
File_upload_max_memory_size: the maximum size of uploaded files (in bytes) that are directly read into the memory ). When the value is greater than this value, the file is stored on the disk. The default value is 2 MB.
File_upload_temp_dir
File_upload_permissions: Permission
File_upload_handlers
The real processor for uploading files. Modify this setting to complete the custom Django File Upload process.
The default value is:
("django.core.files.uploadhandler.MemoryFileUploadHandler","django.core.files.uploadhandler.TemporaryFileUploadHandler",)
First try to load the memory, if not, it will be saved to the temporary file.
File Upload encapsulation method:
'''File upload''' def handle_uploaded_file (F): file_name = "" try: Path = "Media/image" + time. strftime ('/% Y/% m/% d/% H/% m/% S/') if not OS. path. exists (PATH): OS. makedirs (PATH) file_name = path + F. name Destination = open (file_name, 'wb + ') for chunk in F. chunks (): destination. write (chunk) destination. close () failed t exception, E: Print e return file_name
Category: Django Tag: Django file, Django image, Django file upload, Django file management, Django configuration file
Django Upload File