FileDownload.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * 根据后台接口文件流下载
  3. * @param {*} data
  4. * @param {*} filename
  5. * @param {*} mime
  6. * @param {*} bom
  7. */
  8. export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
  9. const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
  10. const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
  11. if (typeof window.navigator.msSaveBlob !== 'undefined') {
  12. window.navigator.msSaveBlob(blob, filename);
  13. } else {
  14. const blobURL = window.URL.createObjectURL(blob);
  15. const tempLink = document.createElement('a');
  16. tempLink.style.display = 'none';
  17. tempLink.href = blobURL;
  18. tempLink.setAttribute('download', filename);
  19. if (typeof tempLink.download === 'undefined') {
  20. tempLink.setAttribute('target', '_blank');
  21. }
  22. document.body.appendChild(tempLink);
  23. tempLink.click();
  24. document.body.removeChild(tempLink);
  25. window.URL.revokeObjectURL(blobURL);
  26. }
  27. }
  28. /**
  29. * 根据文件地址下载文件
  30. * @param {*} sUrl
  31. */
  32. export function downloadByUrl({
  33. url,
  34. target = '_blank',
  35. fileName,
  36. }: {
  37. url: string;
  38. target?: TargetContext;
  39. fileName?: string;
  40. }): boolean {
  41. const isChrome = window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  42. const isSafari = window.navigator.userAgent.toLowerCase().indexOf('safari') > -1;
  43. if (/(iP)/g.test(window.navigator.userAgent)) {
  44. console.error('您的浏览器不支持下载!');
  45. return false;
  46. }
  47. if (isChrome || isSafari) {
  48. const link = document.createElement('a');
  49. link.href = url;
  50. link.target = target;
  51. if (link.download !== undefined) {
  52. link.download = fileName || url.substring(url.lastIndexOf('/') + 1, url.length);
  53. }
  54. if (document.createEvent) {
  55. const e = document.createEvent('MouseEvents');
  56. e.initEvent('click', true, true);
  57. link.dispatchEvent(e);
  58. return true;
  59. }
  60. }
  61. if (url.indexOf('?') === -1) {
  62. url += '?download';
  63. }
  64. window.open(url, target);
  65. return true;
  66. }