vue In the form of file stream blob Download export file operation

  • 2021-08-06 19:55:16
  • OfStack

In vue projects, files are often exported and downloaded, sometimes directly returned to the server file url, so as to download directly with a link, or download or preview different types of files with windown. open. However, if you return a file stream, you need to do 1 other processing, which takes the following form:

1. First, determine the data type returned by the server.

Add: config. responseType = 'blob' to the request header

Sometimes, if not all interfaces need this type, you can make one decision for the interface:


// request Interceptor 
service.interceptors.request.use(
 config => {     //  According to the interface decision 
  if ( config.url === '/setting/exportData' ||
  config.url.indexOf('export') > -1 ||
  config.url.indexOf('Export') > -1) {
   config.responseType = 'blob' //  Service request type 
  }
  if (getToken()) {
   config.headers['access_token'] = getToken()
  }
  return config
 },
 error => {
  // Do something with request error
  // console.log(error) // for debug
  Promise.reject(error)
 }
)

2. The interface requests to obtain the file stream returned by the backend


//  Export 
  onExport() {
   if (this.dataList === '') {
    this.$message({
     type: 'error',
     message: ' There is no data export at present '
    })
    return
   }
   const fd = new FormData()
   fd.append('id', this.id)
   var exportFileName = ' Export file name ' // Set the exported file name, which can be spliced 1 Random values 
   exportData(fd)
    .then(res => {
     // res.data  Is the file stream returned by the backend 
     //  Call  downloadUrl  Processing files 
     downloadUrl(res.data, exportFileName)
    })
    .catch(err => {
     this.$message({
      type: 'error',
      message: err.message
     })
    })
  },  

3. File processing downloadUrl-This method can be written as a public method for calling


//  Use iframe Framework download file -- With excel As an example, you can modify type And fileName Select a file type 
export function downloadUrl(res, name) {
 const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) //  Structure 1 A blob Object to process data 
 const fileName = name + '.xlsx' //  Export file name 
 const elink = document.createElement('a') //  Create a Label 
 elink.download = fileName // a Tag Add Attribute 
 elink.style.display = 'none'
 elink.href = URL.createObjectURL(blob)
 document.body.appendChild(elink)
 elink.click() //  Perform a download 
 URL.revokeObjectURL(elink.href) //  Release URL  Object 
 document.body.removeChild(elink) //  Release label 
}

4. There are compatibility problems in ie browser, so make some adjustments to downloadUrl


//  Use iframe Framework download file  - Compatibility considerations 
export function downloadUrl(res, name) {
 const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
 // for IE
 if (window.navigator && window.navigator.msSaveOrOpenBlob) {
  const fileName = name + '.xlsx'
  window.navigator.msSaveOrOpenBlob(blob, fileName)
 } else {
  // for Non-IE (chrome, firefox etc.)
  const fileName = name + '.xlsx'
  const elink = document.createElement('a')
  elink.download = fileName
  elink.style.display = 'none'
  elink.href = URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href)
  document.body.removeChild(elink)
 }
}

Summary: At this point, one way to export files in the form of file stream has been implemented.

Additional knowledge: In vue, file stream is used for downloading (new Blob) without opening a new page for downloading

I won't talk too much, let's just look at the code ~


export function download (url, params, filename) {
 
 Message.warning(' In the exported data ')
 return axios.get(url, {
  params: params,
  responseType:'arraybuffer',
 }).then((r) => {
 
  const content = r.data
  const blob = new Blob([content],{type:'application/vnd.ms-excel'})
  if ('download' in document.createElement('a')) {
   const elink = document.createElement('a')
   elink.download = filename
   elink.style.display = 'none'
   elink.href = URL.createObjectURL(blob)
   document.body.appendChild(elink)
   elink.click()
   URL.revokeObjectURL(elink.href)
   document.body.removeChild(elink)
   Message.success(' Export succeeded ')
 
  }
 
 }).catch((r) => {
  console.error(r)
  Message.error(' Export failed ')
 
 })
}

Related articles: