zipdownload.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import axios from 'axios'
  2. import { getToken } from '@/utils/auth'
  3. import { Message } from 'element-ui'
  4. const mimeMap = {
  5. xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  6. zip: 'application/zip'
  7. }
  8. const baseUrl = process.env.VUE_APP_BASE_API
  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. if(result == null) {
  33. Message.error("附件为空");
  34. return
  35. }
  36. var fileName = result[1]
  37. fileName = fileName.replace(/\"/g, '')
  38. aLink.href = URL.createObjectURL(blob)
  39. aLink.setAttribute('download', fileName) // 设置下载文件名称
  40. document.body.appendChild(aLink)
  41. aLink.click()
  42. document.body.appendChild(aLink)
  43. }