js的使用原生的XMLHttpRequest上傳文件


原來的XMLHttpRequest對象的缺點:

1.只支持文本數據的傳遞,不支持二進制數據。

2.傳遞數據的時候,沒有progress事件,不能實時顯示傳遞的進度信息。

3.受同源策略的限制,不能發送跨域的請求。

新標准的XMLHttpRequest的改進:

1.可以傳遞二進制數據。

2.在服務器端設置了CORS允許跨域請求的時候,可以獲取跨域的數據。

3.可以使用原生的FormData對象來管理要發送的表單數據。

4.提供了progress事件,可以提供進度信息。在下載和上傳的時候,都有progress事件,下載的時候,progress事件由XMLHttpRequest本身觸發,上傳的時候,由XMLHttpRequest.upload對象觸發,可以通過addEventListener來添加事件處理方法。

 

利用新標准的XMLHttpRequest對象,我們可以非常方便的實現文件AJAX上傳功能。

html:

<!DOCTYPE html>

<html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>使用XMLHttpRequest上傳文件</title>
        <style type="text/css">
            .container {
                width: 500px;
                margin: 0 auto;
            }
            .progress-bar {
                border: 1px solid #000;
            }
            .progress {
                width: 0;
                background: #DEDEDE;
                height: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <p>
                選擇文件:
                <input type="file" id="ipt-file"/>
                <button type="button" id="btn-upload">上傳</button>
            </p>
            <div class="progress-bar">
                <div class="progress"  id="progress"></div>
            </div>
            <p id="info"></p>
        </div>
        <script src="./js/upload.js"></script>
    </body>
</html>
 
uplod.js
 
var button = document.querySelector("#btn-upload"),
    input = document.querySelector("#ipt-file"),
    progress = document.querySelector("#progress"),
    info = document.querySelector("#info");
 
var upload = function() {
    if (input.files.length === 0) {
        console.log("未選擇文件");
        return;
    }
 
    var formData = new FormData();
    formData.append("file", input.files[0]);
 
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText);
            info.innerHTML = xhr.responseText;
        }
    };
 
    xhr.upload.addEventListener("progress"function(event) {
        if(event.lengthComputable){
            progress.style.width = Math.ceil(event.loaded * 100 / event.total) + "%";
        }
    }, false);
 
    xhr.open("POST""./upload");
    xhr.send(formData);
};
 
button.addEventListener("click", upload, false);
 
摘抄於原文請參考:參考地址,謝謝


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM