1. /**
    2. ● 下载文件
    3. ● @param {String} path - 下载地址/下载请求地址。
    4. ● @param {String} name - 下载文件的名字/重命名(考虑到兼容性问题,最好加上后缀名)
    5. */
    6. function downloadFile (path, name) {
    7. const xhr = new XMLHttpRequest();
    8. xhr.open('get', path);
    9. xhr.responseType = 'blob';
    10. xhr.send();
    11. xhr.onload = function () {
    12. if (this.status === 200 || this.status === 304) {
    13. // 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob
    14. if ('msSaveOrOpenBlob' in navigator) {
    15. navigator.msSaveOrOpenBlob(this.response, name);
    16. return;
    17. }
    18. // const blob = new Blob([this.response], { type: xhr.getResponseHeader('Content-Type') });
    19. // const url = URL.createObjectURL(blob);
    20. const url = URL.createObjectURL(this.response);
    21. const a = document.createElement('a');
    22. a.style.display = 'none';
    23. a.href = url;
    24. a.download = name;
    25. document.body.appendChild(a);
    26. a.click();
    27. document.body.removeChild(a);
    28. URL.revokeObjectURL(url);
    29. }
    30. };
    31. }