Search code examples
vue.jsaxiosblob

How do I handle errors when responseType is blob using Vuejs?


My Question is similar to this which doesn't have an answer. I tried to search many other places but still don't have an answer.

I'm trying to download file using Axios in VueJs as a blob:

return new Promise((resolve, reject) => {
      Axios.get(`${fileDownloadUrl}`,
        { responseType: 'blob' } // Blob doesn't handle errors
      ).then(response => {
        let byteData = response.data
        var blob = new Blob([byteData], {type: response.headers['content-type']})
        let fileName = _.split(response.headers['content-disposition'], '=')
        FileSaver.saveAs(blob, fileName[1])
        resolve(fileName[1])
      },
        error => {
          console.log(error.response.data) // returns Blob - error message from service is not handled
          reject(error.response.data)
        }
      )

I removed the { responseType: 'blob' } from the above code and tried again, I get the error message now but the file downloaded doesn't have any content, it's a blank data.

How do I download the file and handle the error response returned by the service?


Solution

  • Using vue-resource solved this issue. Although it will be retiring in future releases, I couldn't find a better way to do it as Axios was not able to handle it.

    Following is the code:

    main.js

    import VueResource from 'vue-resource'
    Vue.use(VueResource)
    

    service.js

    return new Promise((resolve, reject) => {
      VueResource.http.get(`${fileDownloadUrl}`,
        { responseType: 'blob' }
      ).then(response => {
        methods.downloadFile(response, cid)
        resolve(cid)
      }, error => {
        reject(error)
      })
    })
    

    Hope this helps.