downloadFile.ts 968 B

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * 下载文件
  3. * @param url 下载链接
  4. * @param filename 文件名
  5. */
  6. export function downloadFile(url: string, filename: string | undefined = undefined) {
  7. const urlSplit = url.split('/');
  8. filename = filename || urlSplit[urlSplit.length - 1];
  9. const link = document.createElement('a');
  10. link.setAttribute('download', filename);
  11. link.href = url;
  12. document.body.appendChild(link);
  13. link.click();
  14. document.body.removeChild(link);
  15. window.URL.revokeObjectURL(url);
  16. }
  17. /**
  18. * 文件流下载
  19. * @param res
  20. */
  21. export function downloadStreamFile(res: any) {
  22. const contentType = res.headers['content-type'];
  23. const contentDisposition = res.headers['content-disposition'];
  24. const filename = decodeURIComponent(contentDisposition.split('; ')[1].split('=')[1])
  25. const blob = res.data instanceof Blob ? res.data : new Blob([res.data], { type: contentType });
  26. downloadFile(window.URL.createObjectURL(blob), filename);
  27. }