1.我们下载文件可以通过创建超链接a的形式,也可以通过文件流的方式。
- downloadFile(sourceUrl,fileName) {
- const link = document.createElement('a');
- link.style.display = 'none';
- // 设置下载地址
- link.setAttribute('href', sourceUrl);
- // 设置文件名
- link.setAttribute('download', fileName);
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
2.上述方式下载文件无法命名文件,改成一下方式就可以。
- downloadFile(sourceUrl,fileName) {
- const xhr = new XMLHttpRequest();
- xhr.open('GET', sourceUrl, true);
- xhr.responseType = 'blob';
- xhr.onload = function () {
- if (xhr.status === 200) {
- const res = xhr.response;
- const link = document.createElement('a');
- link.style.display = 'none';
- const url = window.URL.createObjectURL(res);
- link.href = url;
- link.setAttribute('download', fileName);
- document.body.appendChild(link);
- link.click();
- window.URL.revokeObjectURL(link.href);
- document.body.removeChild(link);
- }
- }
- xhr.send()
- },