XMLHttpRequest.prototype.upload

upload属性返回一个XMLHttpRequestUpload对象,用于描述当前资源上传的进度。

我们可以通过返回对象的onprogress属性实时监听上传的进度:

xhr.upload.onprogress = updateProgress;
function updateProgress(event) {
    if (event.lengthComputable) {
      var completedPercent = event.loaded / event.total; //该变量表示上传的进度
    }
}

语法

xhr.upload

返回值

返回一个 XMLHttpRequestUpload 对象。

示例

<form action="" method="post">
    <input type="text" name="user_name" />
    <input type="file" name="user_file" />
    <button type="submit">Submit</button>
</form>

<script>
var form = document.querySelector("form");

form.addEventListener("submit", function (e) {
    var fdata = new FormData(this);

    // Optional. Append custom data.
    fdata.append('user_city', 'Los Angeles');

    ajaxFileUpload(fdata);

    // Prevents the standard submit event
    e.preventDefault();
    return false;
}, false);

var ajaxFileUpload = function (data) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "ajax-upload.php", true);
    xhr.upload.onprogress = function (event) {
        if (event.lengthComputable) {
          var completedPercent = event.loaded / event.total; //该变量表示上传的进度
        }
    };
    xhr.send(data);
};

</script>

相关链接