views.py
def upload_img (Request):
Nid=str (Uuid.uuid4 ())
ret={' status ': True, ' data ': none, ' message ': none}
Obj=request. Files.get (' K3 ')
File_path=os.path.join (' static ', nid+obj.name)
F=open (File_path, ' WB ')
For line in Obj.chunks ():
F.write (line)
F.close ()
ret[' Data ']=file_path
Return HttpResponse (Json.dumps (ret))
Index.html
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>Title</title>
<style>
. btn{
Display:inline-block;
padding:5px 10px;
Background-color:coral;
Color:white;
}
</style>
<body>
<iframe 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= "K3" onchange= "UploadFile ();"/>
</form>
<div id= "Preview" >
</div>
<script src= "/static/js/jquery-3.1.1.js" ></script>
<script>
function UploadFile () {
document.getElementById (' iframe1 '). onload = reloadIframe1;
document.getElementById (' FM1 '). Submit ();
}
function reloadIframe1 () {
var content = This.contentWindow.document.body.innerHTML;
var obj = json.parse (content);
var tag = document.createelement (' img ');
TAG.SRC = Obj.data;
$ (' #preview '). Empty (). append (tag);
}
</script>
</body>
Ajax---Uploading images and previews