Skip to content
Advertisement

Chunk file upload with axios

I encountered a problem and was hopeing someone could help me. I need to realize file chunk upload with axios, and I need to send the chunks to my server one after the other. So new axios request should happen after the previous one is completed. Now, requests are not sent in order. my code is below:

  addChunk(file) { // I receive file from my file uploader 
  this.getBase64(file[0].file).then((base64) => {
    this.convertChunks = base64.replace(base64.substring(0, base64.search(',') + 1), '')
    this.convertedArr = this.convertChunks .match(/.{1,500000}/g) //here I convert it into base64 with helper function
  })
  for (let i in this.convertedArr) {
    if (this.uploadSuccess === false) return null
      axios({
        url: `${domain}`,
        method: 'POST',
        data: [this.convertedArr[i]]
      })
        .then(() => {
          if (parseInt(i) === this.convertedArr.length - 1) {
            this.nextFunction()  //after the last chunk is sent successfully, i need to call another function
          }
        })
        .catch((error) => {
          console.log(error)
        })
  }
},

Advertisement

Answer

Use the async / await syntax to make it possible for your method to wait for the axios request to finish.

Also switch to for...of instead of for...in. The latter is used loop over enumerable properties of an object, and although it an be used on an array, it should be avoided when order is important.

Expand the for...of by looping over the this.convertedArr.entries(). This will create an array with [ index, value ] for each item in the array, so this enables you to use the index.

With try...catch...finally you can catch any errors an awaited function call might produce. The finally part is there to make sure that that part is called if either the request has been successful or failed.

async addChunk(file) { // I receive file from my file uploader 
  this.getBase64(file[0].file).then((base64) => {
      this.convertChunks = base64.replace(base64.substring(0, base64.search(',') + 1), '')
      this.convertedArr = this.convertChunks.match(/.{1,500000}/g) //here I convert it into base64 with helper function
  })

  for (const [ i, item ] of this.convertedArr.entries()) {
    if (this.uploadSuccess === false) return null

    try {
      await axios({
        url: `${domain}`,
        method: 'POST',
        data: [item]
      });
    } catch(error) {
      console.log(error)
    } finally {
      if (parseInt(i) === this.convertedArr.length - 1) {
        this.nextFunction();
      }
    }
  }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement