Download files using the A label

  1. The project needs to download the background execl file, download through the interface, use JS document flow
  2. Create a separate JS file and use it locally
export function $_downloadFile(obj, name, suffix) {
  const DOWNLOAD_TYPE_MAP = {
    xls: 'application/vnd.ms-excel'.xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'.doc: 'application/msword'.docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'.pdf: 'application/pdf'
  }
  if(! DOWNLOAD_TYPE_MAP[suffix]) {throw new Error('Please pass in the file download format suffix eg: XLS, XLSX, doc, docx, PDF')}const blob = new Blob([obj], {
    type: DOWNLOAD_TYPE_MAP[suffix]
  })
  const fileName = `${name}.${suffix}`
  let link = document.createElement('a')
  document.body.appendChild(link)
  link.href = URL.createObjectURL(blob)
  link.setAttribute('download', fileName)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(link.href) // Destroy the URL object
}

Copy the code

Use 3.

/ / interface
export function exportExcel(data) {
  return request({
    url: '/item/exportExcel'.method: 'get'.responseType: 'blob'.// If you want to add it, it won't work
    params: { ...data }
  })
}

/ / usage
import { $_downloadFile } from '@/utils/download'
// used in the interface
exportExcel(queryData)
   .then(res= > {
    $_downloadFile(res, 'Export file name'.'xlsx')  //res: returns data
   })
  .catch(() = > {})
Copy the code

True and effective can be used hereby record!!