You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

downloadfile.ts 2.2 kB

2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { request } from '@umijs/max';
  2. const mimeMap = {
  3. xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  4. zip: 'application/zip',
  5. };
  6. /**
  7. * 解析blob响应内容并下载
  8. * @param {*} res blob响应内容
  9. * @param {String} mimeType MIME类型
  10. */
  11. export function resolveBlob(res: any, mimeType: string) {
  12. const aLink = document.createElement('a');
  13. const blob = new Blob([res.data], { type: mimeType });
  14. // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  15. const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
  16. // console.log(res);
  17. const contentDisposition = decodeURI(res.headers['content-disposition']);
  18. const result = patt.exec(contentDisposition);
  19. let fileName = result ? result[1] : 'file';
  20. fileName = fileName.replace(/"/g, '');
  21. aLink.style.display = 'none';
  22. aLink.href = URL.createObjectURL(blob);
  23. aLink.setAttribute('download', fileName); // 设置下载文件名称
  24. document.body.appendChild(aLink);
  25. aLink.click();
  26. URL.revokeObjectURL(aLink.href); // 清除引用
  27. document.body.removeChild(aLink);
  28. }
  29. export function downLoadZip(url: string, params: any) {
  30. request(url, {
  31. method: 'GET',
  32. params,
  33. responseType: 'blob',
  34. getResponse: true,
  35. }).then((res) => {
  36. resolveBlob(res, mimeMap.zip);
  37. });
  38. }
  39. export async function downLoadXlsx(url: string, params: any, fileName: string) {
  40. return request(url, {
  41. ...params,
  42. method: 'POST',
  43. responseType: 'blob',
  44. }).then((data) => {
  45. const aLink = document.createElement('a');
  46. const blob = data as any; // new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  47. aLink.style.display = 'none';
  48. aLink.href = URL.createObjectURL(blob);
  49. aLink.setAttribute('download', fileName); // 设置下载文件名称
  50. document.body.appendChild(aLink);
  51. aLink.click();
  52. URL.revokeObjectURL(aLink.href); // 清除引用
  53. document.body.removeChild(aLink);
  54. });
  55. }
  56. export function download(fileName: string) {
  57. window.location.href = `/api/common/download?fileName=${encodeURI(fileName)}&delete=${true}`;
  58. }