I haven’t paid attention to nuggets for a long time, because I am very busy these days, tomorrow’s Mid-Autumn Festival, I wish everyone a happy Mid-Autumn festival in advance!!

This is the summary of downloading the EXCEL file. If you have any questions, you can make suggestions. I think this will make us grow up together.

Solution Process (I)

I came across downloading EXCEL files in development, and my immediate thought was to use links to download them,

Example: EXCEL However, this will have a big disadvantage, is that someone may attack the server, because there is no build right, so you can always download your files.

Solution Process (II)

Then I went to improve, but with this is similar, using JS to download.

Ex. :

function handleDownloadExcel () {
    let a = document.createElement('a')
    a.href = "Https://www.juejin.com/ test. XLS"
    a.download = "Test. XLS"
    a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))
}
Copy the code

This code is intended to be compatible with Firefox

a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))

Solution Process (3)

The above method is not the best, because our background must give me base64, can only obey, because I sleep (say) disobey them

Ex. :

function handleDownloadExcel () {
    let base64 = 'data:application/vnd.ms-excel; base64,'
    let a = document.createElement('a')
    a.href = base64 + respone.data
    a.download = "Test. XLS"
    a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))
}
Copy the code

But this download down is wrong, there is no content, so I think base64 excel can not download, who has what good download base64 excel file method can comment, learn from each other.

Solution Process (4)

I searched the web and tried many methods, and the best I saw was to get the background to give you binary data in Blob format. Go straight to code

 handleDownloadExcel () {
      downloadExcel({
        data: data
      })
        .then(res => {
          this.isShowBtnLoading = false
          this.isBtnDisabled = false
          let blob = new Blob([res])
          let a = document.createElement('a') a.href = url.createObjecturl (blob) a.daownLoad = 'test.xls' a.DaisPatchEvent (new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))
        })
        .catch(err => {
          console.log(err)
        })
    }
Copy the code

I use the VUE framework, and of course the plugin is Axios

Request method to give you an example, why give you this example? Because responseType: ‘blob’, that’s a must, and I also made a mistake, as you can see in the code below, because I wrapped this AXIos, so I’m definitely going to do a return intercept, and the binary that was given in the background can’t be put in data, so I have to return response directly, So I didn’t do if(code === 200){·····} in the above code, if you do what I do, remember to filter out the return from this interface in your return interception, If (response.data.type === ‘application/vnd.ms-excel’) {return response.data}, then you can download it directly.

export let downloadExcel = function (data) {
  return request({
    method: 'get',
    url: URL.DOWNLOAD_EXCEL,
    responseType: 'blob',
    params: data
  })
}
Copy the code

Subsequent 2019.11.28

Because the above solution could not get the code returned by the background, and my background did not want to send binary to me, but still wanted to send base64 to me, so I began to optimize, and racked my brains to think, in fact, it is very simple to convert Base64 to binary file stream and then download. Go straight to code

functionparseExcel (b64Data, Filename) {var sliceSize = 512 var byteCharacters = window.atob(b64Data) var byteArrays = []for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize)
    var byteNumbers = new Array(slice.length)
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }
    var byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }
  let file = new File(byteArrays, filename, {type: 'application/vnd.ms-excel; charset=utf-8'})
  let blob = new Blob([file])
  let a = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  a.download = `${filename}.xls`
  a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))
}
export default parseExcel
Copy the code

conclusion

  • Be sure to addResponse: 'blob'
  • createnew Blob([res])
  • withURL.createObjectURL(blob)To create the address
  • Please follow my blog Max