download.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const parseDownloadFilename = dispositionInfo => {
  2. if (!dispositionInfo) return;
  3. const strs = dispositionInfo.split(";");
  4. let filename = "";
  5. strs
  6. .map(item => item.split("="))
  7. .find(item => {
  8. if (item[0].indexOf("filename") !== -1) {
  9. filename = decodeURI(item[1]);
  10. }
  11. });
  12. return filename;
  13. };
  14. /**
  15. * 通过api下载文件
  16. * @param {AxiosPromise} fetchFunc 下载接口
  17. * @param {String}} fileName 文件名
  18. * @returns Promise<Boolean>
  19. */
  20. export function downloadByApi(fetchFunc, fileName) {
  21. return fetchFunc()
  22. .then(res => {
  23. const filename =
  24. fileName || parseDownloadFilename(res.headers["content-disposition"]);
  25. downloadByBlob(new Blob([res.data]), filename);
  26. return true;
  27. })
  28. .catch(e => {
  29. return Promise.reject(e);
  30. });
  31. }
  32. /**
  33. * 下载blob
  34. * @param {Blob} data blob对象
  35. * @param {String} filename 文件名
  36. */
  37. export function downloadByBlob(data, filename) {
  38. const blobUrl = URL.createObjectURL(data);
  39. downloadByUrl(blobUrl, filename);
  40. }
  41. /**
  42. * 下载url
  43. * @param {String} url 文件下载地址
  44. * @param {String}} filename 文件名
  45. */
  46. export function downloadByUrl(url, filename) {
  47. const tempLink = document.createElement("a");
  48. tempLink.style.display = "none";
  49. tempLink.href = url;
  50. tempLink.setAttribute("download", filename);
  51. if (tempLink.download === "undefined") {
  52. tempLink.setAttribute("target", "_blank");
  53. }
  54. document.body.appendChild(tempLink);
  55. tempLink.click();
  56. document.body.removeChild(tempLink);
  57. window.URL.revokeObjectURL(url);
  58. }
  59. /**
  60. * 下载图片
  61. * @param {String} url 图片地址
  62. * @param {String} filename 下载的文件名
  63. * @returns Promise<Boolean>
  64. */
  65. export function downloadByImgUrl(url, filename) {
  66. return new Promise((resolve, reject) => {
  67. const img = new Image();
  68. // 跨域支持,需要服务端辅助配置
  69. // img.crossOrigin = "";
  70. img.onload = function() {
  71. const canvas = document.createElement("canvas");
  72. const ctx = canvas.getContext("2d");
  73. if (!canvas || !ctx) {
  74. return reject("不支持下载!");
  75. }
  76. canvas.width = img.width;
  77. canvas.height = img.height;
  78. ctx.drawImage(img, 0, 0);
  79. canvas.toBlob(blob => {
  80. downloadByBlob(blob, filename);
  81. resolve(true);
  82. });
  83. };
  84. img.onerror = function(e) {
  85. reject(e);
  86. };
  87. img.src = url;
  88. });
  89. }