1. 程式人生 > >iframe+form完成圖片上傳、圖片預覽功能,期間遇到圖片無法預覽解決django

iframe+form完成圖片上傳、圖片預覽功能,期間遇到圖片無法預覽解決django

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")