Ajax上傳文件 (JQuery Ajax&原生Ajax)

  • Ajax 上傳文件
    • 原生Ajax
    • JQuery Ajax

  • 原生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>
    <input type="file" id="il1">
    <a onclick="upload1();">上傳</a>
    <div id="content"></div>

    <script src="/static/jquery-3.2.1.js"></script>
    <script>
        function upload1() {
            var formData = new FormData();
            formData.append('k1','v1');
            formData.append('fafafa',document.getElementById('il1').files[0]);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    var file_path = xhr.responseText;
                    alert(file_path)
                    var tag = document.createElement('img');
                    tag.src = '/' + file_path;
                    document.getElementById('content').appendChild(tag)
                }
            };
            xhr.open('POST','/upload/');
{#          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');#} // 如果send的是傳formData對象就不用加這條,後臺會對數據進行處理
            xhr.send(formData);
        }
    </script>

</body>

  • JQuery 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>jQuery Ajax上傳文件</h3>
    <input type="file" id="il2">
    <a onclick="upload2();">上傳</a>
    <div id="content2"></div>



    <script src="/static/jquery-3.2.1.js"></script>
    <script>

        function upload2() {
            var formData = new FormData();
            formData.append('k1','v1');
            formData.append('fafafa',$('#il2')[0].files[0]);

            $.ajax({
                url: '/upload/',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false, // 告知jQuery不要加那些請求頭對數據進行處理,把原生的formData傳過去
                success:function (arg) {
                    alert(arg);
                    var tag = document.createElement('img');
                    tag.src = '/' + arg;
                    document.getElementById('content').appendChild(tag)


                }

            })

        }
    </script>

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