I am creating a file upload script that will be split into chunks according to the file size, thus creating multiple requests with different parts of the file, however I would like to put the option where the user can cancel an upload.
This is the function that uploads the file:
function uploadFile(e, uploadID){
var chunks = e.chunks;
var location = e.location;
var cnt = 0;
var end = chunks.length;
var temp =
function callback(cnt){
var e = chunks[cnt];
var xhr = new XMLHttpRequest();
xhr.open("PUT", location, true);
xhr.setRequestHeader('Content-Range', e.range);
xhr.send(e.data);
xhr.onloadend =
function() {
var status = xhr.status;
cnt += 1;
if (status == 308) {
callback(cnt);
} else if (status == 200) {
console.log("Upload feito");
} else {
console.log("Erro: " + xhr.response);
}
};
}(cnt);
}
I know that it is possible to do an abort () on the object to cancel the request, however how can I cancel it only when the user clicks a button? Should I save the XMLHttpRequest () object somewhere to call after or is there some kind of identifier that I can use to cancel the request?
For example, I could set a global variable and save the request object to it, but if I have more than one file being uploaded, how do I keep track of which request should be canceled? Once every new upload the variable will be updated with a new object.