How to cancel an Xmlhttprequest using a button?

Asked

Viewed 115 times

1

I am creating a file upload script that will be divided into Chunks according to the file size, thus creating several requests with different parts of the file, but 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 it is possible to abort() the object to cancel the request, but how can I cancel it only when the user clicks a button? Should I save the Xmlhttprequest() object somewhere to call later or is there some type of identifier 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 to cancel? Since every new upload the variable will be updated with a new object.

  • @dvd I know it is possible to use abort(), my problem is how do I call it through a button? And then if I have multiple uploaded files the variable that contains the object will change each time a new file is uploaded. I want to know how to recognize which upload should be canceled.

1 answer

1


Use the method abort: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

// 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 for aborting a specific request.

Just run abortar() at the click of the button.
Before executing the abort check the status of the request in xhr.status : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status

  • 1

    who voted negative may explain what is useless or wrong in the answer by kindness?

  • Employee well if it was to upload 1 file at a time, if I have more than 1 file, every new file var xhr will be updated with a new object

  • in this case, either cancel all or just one particular upload?

  • One in particular, the one the user chooses, so it would help me to know if there is an ID for the requests or something similar

  • 1

    see the issue I asked in the question. XMLHttpRequest does not have an identifier, but you can assign one to a list when storing the request, and delete that particular

  • Also did not understand the -1, the answer seems completely valid

  • Interesting, instead of saving to a global variable, do I have other options to save to? Since these are functions that will be called different scripts, I don’t want to risk suffering with variable scopes

  • 1

    The variable in this example still ends up being global. If you need to access different scripts, all scripts would need to access the variable. About saving is possible, but this works well with data numbers, texts, or even simpler classes. In this case as is an object of XMLHttpRequest I don’t know how serialization would work, I would need to test. In this case the localStorage could be an option, but I would still try with the global variable.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.