zipdownload.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import axios from 'axios'
  2. import storage from 'store'
  3. import { ACCESS_TOKEN } from '@/store/mutation-types'
  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 ' + storage.get(ACCESS_TOKEN) }
  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. console.log(result)
  33. var fileName = result[1]
  34. fileName = fileName.replace(/"/g, '')
  35. aLink.href = URL.createObjectURL(blob)
  36. aLink.setAttribute('download', fileName) // 设置下载文件名称
  37. document.body.appendChild(aLink)
  38. aLink.click()
  39. document.body.appendChild(aLink)
  40. }