image.png

  1. export const downloadFile = (data, fileName,mimetypes) => {
  2. var blob = new Blob([data], {
  3. type: mimetypes
  4. })
  5. var href = window.URL.createObjectURL(blob) //创建下载的链接
  6. if (window.navigator.msSaveBlob) {
  7. // ie 浏览器
  8. window.navigator.msSaveBlob(blob, fileName)
  9. } else {
  10. // 谷歌浏览器 创建a标签 添加download属性下载
  11. var downloadElement = document.createElement('a')
  12. downloadElement.href = href
  13. downloadElement.target = '_blank'
  14. downloadElement.download = fileName //下载后文件名
  15. document.body.appendChild(downloadElement)
  16. downloadElement.click() //点击下载
  17. document.body.removeChild(downloadElement) //下载完成移除元素
  18. window.URL.revokeObjectURL(href) //释放掉blob对象
  19. }
  20. }

⚠️注意 :axios 请求时添加 responseType: ‘blob’,

常用 mimetypes

mimetypes mimes
“image/jpeg” “jpg”
“image/jpeg” “jpeg”
“image/png” “png”
“image/webp” “webp”
“application/vnd.ms-excel” “xls”
“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet” “xlsx”
“application/msword” “doc”
“application/vnd.openxmlformats-officedocument.wordprocessingml.document” “docx”
“application/vnd.openxmlformats-officedocument.presentationml.presentation” “pptx”
“application/vnd.ms-powerpoint” “ppt”
“application/pdf” “pdf”