Search code examples
javascriptexcelvue.jsblobxlsx

How download Excel file in Vue.js application correctly?


I'm struggling to download an Excel file in xlsx format in my Vue.js application. My Vue.js application make post request to the Node.js application which download that Excel file from remote SFTP server. Backend application works without any problems.

In Vue.js application I use next code:

axios.post(config.backendHost + '/excel', {
  file_name: fileName
}).then((response) => {
  const url = URL.createObjectURL(new Blob([response.data], {
    type: 'application/vnd.ms-excel'
  }))
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
});

After downloading file by browser, file opens automatically and I am experiencing an error that looks like this:

We found a problem with some content .xlsx. Do you want us to try and recover as much as we can?


Solution

  • You need to add the response type as a third argument in your post call

    {
        responseType: 'blob'
    }
    

    Your final code like that

    axios.post(config.backendHost + '/excel', {
        file_name: fileName
    }, {
        responseType: 'blob'
    }).then((response) => {
        const url = URL.createObjectURL(new Blob([response.data], {
            type: 'application/vnd.ms-excel'
        }))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
    });
    

    Or you can use the library FileSaver.js to save your file

    import FileSaver from 'file-saver'
    
    axios.post(config.backendHost + '/excel', {
        file_name: fileName
    }, {
        responseType: 'blob'
    }).then((response) => {
    
        // response.data is a blob type
        FileSaver.saveAs(response.data, fileName);
    });