1 Template Template file uploadfile.html
It is important to note that request is only available when the request method is post and the <form> of the request is sent with the attribute enctype= "Multipart/form-data". Files contains file data, otherwise request. Files is empty.
<form method="Post"action=""Enctype="Multipart/form-data"><input type="file"Name="Personico"/><br/><br/><br/><input type="Submit"Value="Submit"/></form>"/static/jpg/{{personico}}"Width="100px"height="100px"alt="Avatar"/>
2 View functions
ifRequest.method = ="POST": F= Request. FILES.Get('Personico') BaseDir=Os.path.dirname (Os.path.abspath (__name__)); Jpgdir= Os.path.join (BaseDir,'Static','jpg'); FileName=Os.path.join (jpgdir,f.name); Fobj= open (filename,'WB'); forChrunkinchf.chunks (): Fobj.write (Chrunk); Fobj.close (); returnRender_to_response ('uploadfile.htm',{'Personico': F.name}); Else: returnRender_to_response ('uploadfile.htm');
Here: The uploaded files are stored in the project directory under the static/jpg/directory, the filename is the file name of the upload, only experimental so no error verification, if used in production environment, need to be strictly verified, such as the existence of files, read and write errors, etc.
The uploaded file is in Request. Files, which is a data type of approximate dictionary type, has basic 4 basic properties, name filename/size file size (in bytes)/content_type file type/read file contents
The owning method chunks () returns a block builder for an uploaded file, with an optional parameter that sets the number of bytes per read. If the uploaded file is large, using this method saves memory and does not take up a lot of memory space at a sudden.
Where to save the uploaded file
Before saving the uploaded file, the data needs to be stored in a certain location. By default, when the upload file is less than 2.5M, Django reads the entire contents of the uploaded file into memory. means that the save file is read from memory only once, one write disk at a time.
But when the upload file is large, Django writes the uploaded file to the temporary file and then stores it in the system Temp folder.
Three settings to control the behavior of a Django file upload:
File_upload_max_memory_size: The maximum upload file size (in bytes) that is read directly into memory. When the value is greater than this, the file is stored to disk. Default 2.5M bytes
File_upload_temp_dir
File_upload_permissions: Permissions
File_upload_handlers
Upload files to the real processor. Modify this setting to complete the process of customizing the Django upload file.
The default is:
("Django.core.files.uploadhandler.MemoryFileUploadHandler", " Django.core.files.uploadhandler.TemporaryFileUploadHandler ",)
Try to load the memory first, and then deposit it to a temporary file if it doesn't work.
Experimental results:
Pre-upload effect
Post-upload effect
Process file Upload file in Django