ifram+form方式實現檔案、圖片上傳、預覽

來源:互聯網
上載者:User

標籤:win   onchange   add   iframe   function   前端   tar   img   this   

1、前端代碼

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <style>        .btn{            display: inline-block;            padding: 5px 10px;            background-color: coral;            color: white;        }    </style></head><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="k1" onchange="uploadFile();" />    </form>    <h3>預覽</h3>    <div id="preview">    </div>    <script src="/static/js/jquery-3.1.1.js"></script>    <script>         //檔案上傳控制項綁定onchange事件,當有檔案上傳就觸發表單提交        function uploadFile() {            document.getElementById(‘iframe1‘).onload = reloadIframe1;            document.getElementById(‘fm1‘).submit();        }        //取得iframe控制項的傳回值,並將值取出進行json還原序列化,        function reloadIframe1() {            var content = this.contentWindow.document.body.innerHTML;            var obj = JSON.parse(content);            //建立img控制項,並將遠端的圖片地址賦予image。            var tag = document.createElement(‘img‘);            tag.src = obj.data;            $(‘#preview‘).empty().append(tag);        }    </script></body></html>   

 

2、後端代碼

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‘)    for line in obj.chunks():        f.write(line)    f.close()    ret[‘data‘]=file_path    return HttpResponse(json.dumps(ret))

 

ifram+form方式實現檔案、圖片上傳、預覽

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.