django做图片上传时很奇怪预览的时候怎么都加载不到图片,发现图片加载路径含有原来url,所以在图片路径src 最前面加了个“/"解决OK,但是原因还是不清楚,哪位大神解答下,谢谢了。按道理obj.filepath已经包含完整路径了,,搞不明白啊
myimg.src="/"+obj.filepath;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>file upload</title>
<style>
</style>
</head>
<body>
<iframe style="display: none" name="fileiframe" id="imgiframe"></iframe>
<form action="/fileupload/" enctype="multipart/form-data" method="post" target="fileiframe" id="img_form">
<input type="file" name="img" onchange="imgupload()">
</form>
图片预览:
<div id="img_preview" style="border:1px solid #000; width:300px; height:300px;overflow:hidden">
</div>
<script src="/static/jquery-3.3.1.min.js"></script>
<script>
function imgupload(){
//获取iframe返回内容
document.getElementById("imgiframe").onload=reloadimg;
$("#img_form").submit();
}
function reloadimg(){
//获取iframe返回内容
args = this.contentWindow.document.body.innerHTML;
obj = JSON.parse(args)
if(obj.status){
myimg = document.createElement("img")
//这里要加个斜杠,不然显示不出来
//我也不知道为什么,哪个大神解释下
myimg.src="/"+obj.filepath;
//图片自适应大小
myimg.width=300;
myimg.height=300;
console.log(obj.filepath)
//先清空div,然后填充图片
tar = $("#img_preview").empty().append(myimg);
}
}
</script>
</body>
</html>
view.py
from django.shortcuts import render,HttpResponse
import uuid,os,json
def fileupload(request):
if request.method=="POST":
ret={"status":False,"filepath":None}
obj = request.FILES.get("img")
#给要保存的图片命名,obj.name获取原图片名字
file_name = os.path.join("static",str(uuid.uuid4())+obj.name)
buff = open(file_name,"wb")
for item in obj.chunks():
buff.write(item)
buff.close()
ret["status"]=True
ret["filepath"]=file_name
print(file_name)
print(ret["filepath"])
return HttpResponse(json.dumps(ret))
else:
return render(request,"uploadfile.html")