Django uploads the file and queries the data with Django's own models. Model class, to define a Filefield type of storage file, and add a sentence upload_to, as follows: However, if you use MongoDB, although the document has a Filefield type, but there is no upload_to this parameter, so write a method to store the post file in the local
here's how to store files:
def uploaded_file (f,filename):
Address = ' c:/users/xxxx/desktop/' +filename
Destination = open (address, ' wb+ ')
For chunk in F.chunks ():
Destination.write (Chunk)
Destination.close ()
Note: The parameter f is the files file of post, filename is the file name to be stored, the reason is not used a fixed address, because the file type of upload is variable, may also txt, may be jpg, etc.
the upload code in the HTML template:
<form id= "Formid" method= "POST" action= "enctype=" Multipart/form-data ">
<div class= "File-box" >
<input type= ' text ' name= ' Protextfield ' id= ' protextfield ' class= ' txt '/>
<input type= ' button ' class= ' btn ' value= ' Browse ... '/>
<input type= "File" Name= "Proupload" class= "file" id= "Filefield" size= "" onchange= "document.getElementById (' Protextfield '). Value=this.value "/>
<input type= "Submit" name= "Submit" class= "btn" value= "Upload"/>
</div>
</form>
Template Note: form must be added enctype= "Multipart/form-data", otherwise the file cannot be transferred. The
upload operation that the method performs is called in the view.py
def newproject (Request):
If request. FILES:
FileName =request. files[' Proupload '].name
Uploaded_file (Request. files[' Proupload '],filename)
post.proadress = filename
Return Render_to_response (' xxx.html ', locals ())
Description: The filename in the method above is the file name that was uploaded, including the file suffix, such as test.txt. Request. files[' Proupload ') is a file that was obtained with the name Proupload. The result is that the uploaded file is stored in a locally pinned location, and a file name is stored in the database. Other instructions: currently did not do the download, but the next step is to store all the files in a folder, or by the suffix to separate storage, and then download the time according to the file name in the storage folder traversal, take out the file to be searched for download.
Django MongoDB upload file