1. Front-end Code
<! DOCTYPE html>"en">"UTF-8"> <title>Title</title> <style>. btn{Display:inline-Block; padding:5px 10px; Background-color:coral; Color:white; } </style>"Display:none"Id="iframe1"Name="Ifra1"></iframe> <form id="FM1"action="/upload_img.html"Method="POST"Enctype="Multipart/form-data"target="Ifra1"> <input type="file"Name="K1"Onchange="UploadFile ();"/> </form> "Preview"> </div> <script src="/static/js/jquery-3.1.1.js"></script> <script>//the file Upload control binds the onchange event, and when a file is uploaded, it is deliveredfunction UploadFile () {document.getElementById ('iframe1'). onload =reloadIframe1; document.getElementById ('FM1'). Submit (); } //gets the return value of the IFRAME control and takes the value out for JSON deserialization.function reloadIframe1 () {varContent = This. ContentWindow.document.body.innerHTML; varobj =json.parse (content); //creates an IMG control and assigns the image address of the remote to the image. varTag = Document.createelement ('img'); TAG.SRC=Obj.data; $('#preview'). Empty (). append (tag); } </script></body>2. Back-end Code
def upload_img (request): RET={'Status': True,'Data': None} obj= Request. FILES.Get('K1') print (obj) File_path= Os.path.join ('Static', obj.name) F= Open (File_path,'WB') forLineinchobj.chunks (): F.write (line) f.close () ret['Data']=File_pathreturnHttpResponse (Json.dumps (ret))
Ifram+form way to implement file, image upload, preview