在Django中 Iframe + Form 上传文件 图片并预览
def upload(request):
return render(request,'upload.html')
import json,os,uuid
def upload_img(request):
nid=str(uuid.uuid4()) # 防止文件名称相同
ret={"status":True,"data":None,"message":None}
#data存储在服务器的路径
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))
前端显示 upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<iframe style="display: none" id="iframe1" name="ifra1"></iframe>
<form id="fm1" action="/upload_img" method="POST" enctype="multipart/form-data" target="ifra1">
<input type="file" name="k3" onchange="uploadFile()" />
</form>
<div id="preview">//显示图片的位置
</div>
<script src="/static/plugins/bootstrap/js/jquery-3.1.1.min.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);
console.log(obj.data); //obj.data 获取后端图片的路径
var tag=document.createElement("img");
tag.src=obj.data;
$("#preview").empty().append(tag) //先清空内容在添加
}
</script>
</body>
</html>