downloadBlobFile.js 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. import axios from "axios";
  2. function downloadBlobFile(url, data, name, type) {
  3. return new Promise((resolve, reject) => {
  4. axios({
  5. method: type,
  6. url,
  7. responseType: "blob",
  8. data,
  9. })
  10. .then((res) => {
  11. let blob = new Blob([res.data], {
  12. type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
  13. });
  14. let downloadElement = document.createElement("a");
  15. let href = window.URL.createObjectURL(blob); // 创建下载的链接
  16. downloadElement.href = href;
  17. downloadElement.download = name; // 下载后文件名
  18. document.body.appendChild(downloadElement);
  19. downloadElement.click(); // 点击下载
  20. document.body.removeChild(downloadElement); // 下载完成移除元素
  21. window.URL.revokeObjectURL(href); // 释放掉blob对象
  22. resolve({
  23. status: 0,
  24. });
  25. })
  26. .catch((e) => {
  27. reject({
  28. status: 1,
  29. });
  30. });
  31. });
  32. }
  33. export default downloadBlobFile;