user233428
user233428

Reputation: 177

How to cancel file upload in Vue

I have a post method

uploadFile: async function () {
  const formData = new FormData();
  formData.append("file", this.file);
  let url = `http://...`;
  try {
    this.source = axios.CancelToken.source();
    const res = await axios.post(url, formData, {
      headers: {
        Authorization: "Token " + this.$store.getters.getToken,
        "Content-Type": "multipart/form-data",
      },
      cancelToken: this.source.token,
    });
  } catch (error) {
  }
}

and cancel method

  cancelLoad: function () {
      this.source.cancel('cancel upload');
  },

The request was canceled, but after reloading my page, the file uploaded. enter image description here

Upvotes: 0

Views: 1192

Answers (1)

user233428
user233428

Reputation: 177

I've fixed it.

const CancelToken = axios.CancelToken;
let cancel;

const res = await axios.post(url, formData, {
      headers: {...},
      cancelToken: new CancelToken(function executor(c) {
        cancel = c;
      }),
}...

cancel();

Upvotes: 1

Related Questions