Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .abort() an ajax file upload?

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.

like image 610
Wabbitseason Avatar asked Feb 23 '23 19:02

Wabbitseason


1 Answers

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

like image 165
Matthew Manela Avatar answered Feb 27 '23 15:02

Matthew Manela