前端下载如果是文件流的话,就直接使用downloadFile方法进行下载,如果是非文件流,要设置文件名,就要转成文件流的方式,解决通过download设置文件名的兼容问题,代码如下:
download(url, fileName) { function ajax(url, callback, options) { window.URL = window.URL || window.webkitURL; var xhr = new XMLHttpRequest(); xhr.open("get", url, true); if (options.responseType) { xhr.responseType = options.responseType; } xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { callback(xhr); } }; xhr.send(); } function downloadFile(content, filename) { var a = document.createElement("a"); var blob = new Blob([content]); var url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); } ajax( url, function (xhr) { downloadFile(xhr.response, fileName); }, { responseType: "blob", } ); return false; }
标签:function,文件,文件名,url,URL,xhr,window,var,下载 From: https://www.cnblogs.com/sakura-lifangfang/p/16856795.html