最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to .abort() an ajax file upload? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Jun 22, 2011 at 13:47 WabbitseasonWabbitseason 5,6919 gold badges52 silver badges60 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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

发布评论

评论列表(0)

  1. 暂无评论