1. Page code
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Title</title></Head><Body><formAction= "{% url ' upload '%}"Method= "POST"enctype= "Multipart/form-data">{% Csrf_token%}<inputtype= "File"name= "img"> <inputtype= "Submit"></form></Body></HTML>
2. Back-end View function processing
defUpload (Request):ifrequest.method=="GET": returnRender (Request,'upload.html') elifrequest.method=="POST": Res={"Status":"Success","Code": 999} img_obj=request. Files.get ('img')#get File ObjectWith Open (Os.path.join ('Static', Img_obj.name),"WB") as F: forChunkinchImg_obj.chunks (chunk_size=1024): F.write (chunk)returnHttpResponse (Json.dumps (res))
Second, the use of jquery Ajax+formdata implementation upload files |
Upload steps:
1. Page code
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Title</title></Head><Body><formAction= "{% url ' upload '%}"Method= "POST"enctype= "Multipart/form-data">{% Csrf_token%}<inputtype= "File"name= "img"></form><spanstyle= "Padding:5px;color:royalblue"onclick= "Jqajax ();">JQ upload</span><Scripttype= "Text/javascript"src= "/static/jquery-2.1.1.min.js"></Script><Scripttype= "Text/javascript"src= "/static/jquery.cookie.js"></Script><Script> functionJqajax () {varFile_obj=$('input[name= "img"]')[0].files[0];//gets the file object in the Dom form varForm_obj=NewFormData (); //Create a Formdata objectForm_obj.append ('img', File_obj); //load a file object in Formdata$.ajaxsetup ({//Set Csrf_tokenBeforesend:function(XHR, settings) {Xhr.setrequestheader ("X-csrftoken", $.cookie ("Csrftoken")); } }); $.ajax ({type:'POST', URL:'{% URL'Upload' %}', Data:form_obj,//indicates the file object being sentProcessData:false, //tell jquery to transfer the data objectContentType:false, //tell jquery not to increase the request header for ContentType settingsSuccess:function(data) {Console.log (data)}}) }</Script></Body></HTML>
Back-end processing logic does not change
Django File Upload