zipdownload.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import axios from 'axios'
  2. import { getToken } from '@/utils/auth'
  3. import { judgmentNetworkReturnAddress } from "@/utils/ruoyi";
  4. const mimeMap = {
  5. xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  6. zip: 'application/zip'
  7. }
  8. const baseUrl = window.location.href.split('://')[0]+'://' + judgmentNetworkReturnAddress()
  9. export function downLoadZip(str, filename) {
  10. var url = baseUrl + str
  11. axios({
  12. method: 'get',
  13. url: url,
  14. responseType: 'blob',
  15. headers: { 'Authorization': 'Bearer ' + getToken() }
  16. }).then(res => {
  17. resolveBlob(res, mimeMap.zip)
  18. })
  19. }
  20. /**
  21. * 解析blob响应内容并下载
  22. * @param {*} res blob响应内容
  23. * @param {String} mimeType MIME类型
  24. */
  25. export function resolveBlob(res, mimeType) {
  26. const aLink = document.createElement('a')
  27. var blob = new Blob([res.data], { type: mimeType })
  28. // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  29. var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  30. var contentDisposition = decodeURI(res.headers['content-disposition'])
  31. var result = patt.exec(contentDisposition)
  32. var fileName = result[1]
  33. fileName = fileName.replace(/\"/g, '')
  34. aLink.style.display = 'none'
  35. aLink.href = URL.createObjectURL(blob)
  36. aLink.setAttribute('download', fileName) // 设置下载文件名称
  37. document.body.appendChild(aLink)
  38. aLink.click()
  39. URL.revokeObjectURL(aLink.href);//清除引用
  40. document.body.removeChild(aLink);
  41. }