Skip to content Skip to sidebar Skip to footer

How To Cancel A File Upload By Clicking On A 'cancel' Button

I have a form which contains a file input within the form and more importantly a cancel button which should cancel a file upload: var $fileImage = $('

The axios cancel token API is based on the withdrawn cancelable promises proposal.

You can create a cancel token using the CancelToken.source factory as shown below:

constCancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

And to trigger the cancel

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

You can also create a cancel token by passing an executor function to the CancelToken constructor:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

Note: you can cancel several requests with the same cancel token.

doc https://github.com/axios/axios#cancellation

Using XMLHttpRequest:

We use abort() method of the xhr object.

var xhr = newXMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";
xhr.open(method, url, true);

xhr.send();

if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) {
  xhr.abort();
}

doc https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

Solution 2:

There is a possible solution. You can do like that:

$("#cancel").click(function(){
  $("#inputfile").remove();
  $("#containerof_inputfile").append("<input type=\"file\" id=\"inputfile\"/>");
});

Solution 3:

jQuery makes this kind of thing easier. You can call abort on a returned jQuery object. I suppose you can look in the jQuery code to see how it does it if you really want to roll your own.

Edit: I got curious and looked it up. Abort is a method of the XMLHttpRequest function in Javascript.

Post a Comment for "How To Cancel A File Upload By Clicking On A 'cancel' Button"