download.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. * @Author: 范非苗
  3. * @Date: 2021-03-12 11:02:38
  4. * @LastEditTime: 2021-03-12 11:05:07
  5. */
  6. // 文件下载
  7. export const downloadFile = function (url,name) {
  8. const link = document.createElement('a')
  9. link.setAttribute('download', name)
  10. link.href = url
  11. link.click()
  12. }
  13. export const download=function (url,filename="文件下载") {
  14. getBlob(url, function (blob) {
  15. saveAs(blob, filename);
  16. });
  17. }
  18. function getBlob(url, cb) {
  19. var xhr = new XMLHttpRequest();
  20. xhr.open('GET', url, true);
  21. xhr.responseType = 'blob';
  22. xhr.onload = function () {
  23. if (xhr.status === 200) {
  24. cb(xhr.response);
  25. }
  26. };
  27. xhr.send();
  28. }
  29. function saveAs (blob,filename) {
  30. if(window.navigator.msSaveOrOpenBlob){
  31. navigator.msSaveBlob(blob,filename)
  32. }else{
  33. let a=document.createElement("a")
  34. let body=document.querySelector("body")
  35. a.href=window.URL.createObjectURL(blob)
  36. a.download=filename
  37. a.style.display="none"
  38. body.appendChild(a)
  39. a.click()
  40. body.removeChild(a)
  41. window.URL.revokeObjectURL(a.href)
  42. }
  43. }