kennethjiang/js-file-download

when i used js-file-download in npm,something wrong and i could not solve it

homecmx opened this issue · 4 comments

var fileDownload = require('js-file-download');
this.$axios.post( url,
{headers: {
'responseType': 'arraybuffer',
'Accept': 'application/xls'
}}
).then(function(response) {
fileDownload(response.data, 'user.xls');

the download file is unintelligible text.

@Senior-Developers This is some problem with the encoding that is been done from the back end api from where you are getting this response.Check with postman if it works.

axios add responseType: 'blob' config, it work for me.

    axios.get(url, {
      responseType: 'blob',
    })
    .then(((res) => {
        fileDownload(res.data, '11.xls');
     }))

I got base64 data from the server. To use base64 with js-file-download I had to convert the data to a blob. This can be done with the following method:

export const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
  const byteCharacters = atob(b64Data)
  const byteArrays = []

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize)

    const byteNumbers = new Array(slice.length)
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }

    const byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }

  const blob = new Blob(byteArrays, { type: contentType })
  return blob
}

Closing as I believe the question was answered.