Django File upload Download

Source: Internet
Author: User

Views

defMgmt_files (Request):#list tree directories, upload file pages    ifRequest.method = ='POST': Path_root="D:\\py\\itfiles" #上传文件的主目录MyFile=request. Files.get ("file", None)#gets the uploaded file, if there is no file, the default is None        if  notMyfile:dstatus="Please select the file you want to upload!"        Else: Path_ostype= Os.path.join (path_root,request. Post.get ("OSType")) Path_dst_file=Os.path.join (path_ostype,myfile.name)#Print Path_dst_file            ifOs.path.isfile (path_dst_file): Dstatus="%s already exists!"%(myFile.Name)Else: Destination= Open (Path_dst_file,'wb+')#opening a specific file for binary write operations                 forChunkinchMyfile.chunks ():#Block Write fileDestination.write (Chunk) destination.close () Dstatus="%s upload succeeded!"%(myFile.Name)returnHttpResponse (str (dstatus))returnRender (Request,'sinfors/mgmt_files.html')defMgmt_file_download (Request,*args,**kwargs):#provide file download page    #定义文件分块下载函数     defFile_iterator (file_name, chunk_size=512): With open (file_name,'RB'as F: #如果不加 ' RB ' opened in binary mode, the file stream encountered special characters will terminate the download, the downloaded file is  incomplete whileTrue:c=F.read (chunk_size)ifC:yieldCElse:                     BreakPath_root="D:\\py\\itfiles"    ifkwargs['Fpath'] is  notNone andkwargs['fname'] is  notNone:file_fpath= Os.path.join (path_root,kwargs['Fpath']) #kwargs [' fapth '] is the top-level directory name of the file File_dstpath= Os.path.join (file_fpath,kwargs['fname']) #kwargs [' fname '] is the file name Response=Streaminghttpresponse (File_iterator (File_dstpath)) response['Content-type'] ='Application/octet-stream'response['content-disposition'] ='attachment;filename= "{0}"'. Format (kwargs['fname']) #此处kwargs [' fname '] is the file name of the file to be downloaded returnResponse

The Streaminghttpresponse object is used to send the file stream to the browser, very similar to the HttpResponse object, and is more reasonable for file download functionality with Streaminghttpresponse objects. Streamed to the browser through a file stream, but the file flow is often garbled in the browser, instead of downloading to the hard disk, so also do a bit of optimization, let the file stream write to the hard disk, Assign the following values to the Content-type and Content-disposition fields of the Streaminghttpresponse object, such as:

response[' content-type '] = ' application/octet-stream '
response[' content-disposition ' = ' attachment;filename= ' filename.txt "'

HTML page:

 <formID= "Uploadform"enctype= "Multipart/form-data"> //File Upload form {% Csrf_token%}<inputID= "File"type= "File"name= "File" > //Uploading Files             <inputtype= "Radio"name= "OSType"value= "Windows" />Windows<inputtype= "Radio"name= "OSType"value= "Linux" />Linux<inputtype= "Radio"name= "OSType"value= "Network" />Network<inputtype= "Radio"name= "OSType"value= "DB" />DB<ButtonID= "Upload"type= "button"style= "margin:20px">Upload</Button>
</form>

JS Page:

$ ("#upload"). Click (function(){    //Alert (New FormData ($ (' #uploadForm ') [0]));    varOSType = $ (' input:radio:checked '). Val ()if(OSType = =undefined) {Alert (' Please select the file type to upload '); }     //get the value of a radio button$.ajax ({type:' POST ',            //data:$ (' #uploadForm '). Serialize (),DataNewFormData ($ (' #uploadForm ') [0]), ProcessData:false, ContentType:false,//must be false to automatically add the correct content-type            //Cache:false,Successfunction(RESPONSE,STUTAS,XHR) {//parent.location.reload ();              //window.location.reload ();              //alert (stutas);alert (response); },            //error:function (xhr,errortext,errorstatus) {            //Alert (xhr.status+ ' ERROR: ' +xhr.statustext);            // }timeout:6000        }); });

Django File upload download

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.