Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
Nurzhan Nogerbek Avatar asked Sep 20 '19 08:09

Nurzhan Nogerbek


2 Answers

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);
});
like image 169
DibraDev Avatar answered Oct 09 '22 11:10

DibraDev


my case worked:

  axios.get(`/api/v1/companies/${companyId}/export`, {
    responseType: 'blob',
  }).then((response) => {
    const url = URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute(
      'download',
      `${companyId}-${new Date().toLocaleDateString()}.xlsx`
    )
    document.body.appendChild(link)
    link.click()
  })
like image 22
Jorge Epuñan Avatar answered Oct 09 '22 10:10

Jorge Epuñan