How to cancel an XMLHttpRequest using a button?

1

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.

    
asked by anonymous 24.05.2018 / 19:09

1 answer

1

Use the abort method: link

// a variável deve ser global ou ser passada por parâmetro para a function que irá abortar
var xhrList = [];
function uploadFile(e, uploadID){ 
    // aqui deve haver um id que identifique o arquivo (chamei abaixo de "x")
    var xhr = new XMLHttpRequest();
    xhrList.push({ id: x, obj: xhr});
}

function abortar(id) {
  var xhr = xhrList.find(x => x.id === id).obj;
  xhr.abort();
}

EDIT : edited after editing the question explaining the scenario to abort a specific request.

Just run abortar() on the click of the button. Before running abort check the status of the request in xhr.status : link

    
24.05.2018 / 19:15