僞Ajax上傳文件

  • 僞Ajax上傳
    • 之前兩種 (JQuery Ajax&原生Ajax上傳文件) 都要依賴FormData對象進行操作,雖然好用,但兼容性稍微差點,在html5之後提出的對象,現在主流的瀏覽器都支持,ie10以上才能用,其他更老的瀏覽器就不支持FormData對象,這時候就要用僞造Ajax上傳,兼容性好。
# views.py
def upload(request):
    if request.method == 'GET':
        return render(request,'upload.html')
    else:
        print(request.POST,request.FILES)
        file_obj = request.FILES.get('fafafa')
        import os
        file_path = os.path.join('static',file_obj.name)
        with open(file_path,'wb') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)
        return HttpResponse(file_path)


# upload.html

<body>

    <h3>僞 Ajax上傳文件</h3>
        <form id="f1" action="/upload/" target="ifr" method="post" enctype="multipart/form-data">
        <iframe id="ifr" name="ifr" style="display: none"></iframe>
        <input type="file" name="fafafa" />
        <a onclick="upload3();">提交</a>
    </form>
    <div id="content3"></div>



    <script src="/static/jquery-3.2.1.js"></script>
        function upload3() {
        document.getElementById('ifr').onload = loadIframe;
        document.getElementById('f1').submit();

    }
        function loadIframe() {
        var content =  document.getElementById('ifr').contentWindow.document.body.innerText;
        alert(content);
        var tag = document.createElement('img');
        tag.src = '/' + content;
        document.getElementById('content').appendChild(tag)

    }

</body>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章