开发者

How to .abort() an ajax file upload?

开发者 https://www.devze.com 2023-03-15 03:10 出处:网络
I\'m experimenting with ajax-based file uploading following this article, and so far the process is working fine, but I\'ve been unable to find how I could implement an abort button for the file list.

I'm experimenting with ajax-based file uploading following this article, and so far the process is working fine, but I've been unable to find how I could implement an abort button for the file list.

The core code in the article is this:

var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', onprogressHandler, false);
xhr.open('POST', '/upload/uri', true);
xhr.send(file);

function onprogressHandler(evt) {
    var percent = event.loaded/event.total*100;
    console.log('Upload progress: ' + percent + '%');
}

The article mentions that it is possible to define an abort listener:

xhr.upload.onabort = function (evt) {
    console.log("Aborted", evt);
}

According to MDC there's an abort method in the FileReader object, but it is unclear to me how I should use it in this case (or if it is the same "abort" that I'm looking for at all).

What I'd like to have is an abort button next to each file selected for uploading, and开发者_开发技巧 if the user clicks a button then that file should be removed from the list or if its uploading has been started it should be immediately aborted.


There is an abort method on the XMLHttpRequest object. You can do the following: xhr.abort() and that should abort the request.

0

精彩评论

暂无评论...
验证码 换一张
取 消