文件下载
一、调用后端接口下载
- 通过 window.open(url) 下载;
- 通过 window.location = url 下载
- 通过 iframe 下载
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.src = url;
iframe.style.display = 'none';
- 通过点击链接下载
function download(fileName, url) {if (!fileName) return;
console.log(url);
const link = document.createElement('a');
const evt = document.createEvent('MouseEvents');
link.href = url;
link.setAttribute('download', fileName);
evt.initEvent('click');
link.dispatchEvent(evt);
}
二、前端直接下载到本地
- 将数据转换成 Data URLs 后通过 a 标签导出 (以)。
(Data URLs 由四个部分组成:前缀 (data:)、指示数据类型的 MIME 类型、如果非文本则为可选的 base64 标记、数据本身:)
data:[<mediatype>][;base64],<data>
const data = resolveDate(this.data, this.headersMapping);
download('test.csv', `data:'attachment/csv',\ufeff${encodeURIComponent(data)}`);
// data:'attachment/csv',%E5%A7%93%E5%90%8D%2C%E5%B9%B4%E9%BE%84%2C%E7%94%B5%E8%AF%9D%0D%0A%E5%BC%A0%E4%B8%89%2C21%2C13122223839%0D%0A%E6%9D%8E%E5%9B%9B%2C13%2C13198739339%0D%0A%E7%8E%8B%E4%BA%94%2C23%2C13198340239%0D%0A%E6%9D%8E%E9%9B%B7%2C42%2C13198783839%0D%0A%E5%BC%A0%E6%A2%85%E6%A2%85%2C5%2C13198783839%0D%0A%E5%B0%8F%E6%98%8E%2C22%2C13139083839%0D%0A%E5%B0%8F%E7%BA%A2%2C13%2C13198783839%0D%0A%E5%B0%8F%E7%BB%BF%2C11%2C13198783839
- 将数据转换成 blob 格式的 url 后通过 a 标签导出
const data = resolveDate(this.data, this.headersMapping);
const url = window.URL.createObjectURL(new window.Blob([`\ufeff${data}`]));
// blob:http://localhost:8081/9b0d2867-ada2-4db1-b090-d0e8d44e0ae0
downloadFile('test.csv', url);
- 将 canvas 图片下载成 png
const imageData = this.canvas.toDataURL();
// data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAACWCAYAAAA8AXHiAAANmklEQVR4Xu2dB6w9RRXGP4zBBhor9hoQCwh2I3axiwV7FzH2XgB7QQQbViwk2BWDDey9VxALVoxEgwr2QgKKGs2P/2zcXO67d3dnz5nZveckN+8ld+bMzLff3Z09bbZTSCBggMB2BjpDZSCgIFaQwASBIJ...QkTBIJYJrCG0iBWcMAEgSCWCayhNIgVHDBBIIhlAmsoDWIFB0wQCGKZwBpKg1jBARMEglgmsIbSIFZwwASBIJYJrKE0iBUcMEEgiGUCaygNYgUHTBAIYpnAGkqDWMEBEwSCWCawhtIgVnDABIEglgmsoTSIFRwwQSCIZQJrKA1iBQdMEAhimcAaSv8H1TBWtQk/HwUAAAAASUVORK5CYII=
downloadFile('test.jpg', imageData);
const imageData = this.canvas.toDataURL().replace('image/png','image/octet-stream');
// data:image/octetstream;base64,JrKE0iBUcM...ygNYgUHTBnDABIEd3dnz5nZveckN+8ld+bMzLff3Z09bbZTSCBggMB2BjpDZSCgIFaQwASBIJ...QkTBIJYJrCG0iBWcMAEgSCWCayhNIgVHDBBIIhlAmsoDWIFB0wQCGKZwBpKg1jBARMEglgmsIbSIFZwwASBIJYJrKE0iBUcMEEgiGUCaygNYgUHTBAIYpnAGkqDWMEBEwSCWCawhtIgVnDABIEglgmsoTSIFRwwQSCIZQJrKA1iBQglgmsoTSIFRwwQSCIZQJmcAaSv8H1TBWtQk/HwUAAAAASUVORK5CYII=
downloadFile('test2.png', imageData);
打印
<div class="print">...</div>
.print {page-break-after: always;}
@page {margin: 0;}
组件化后,需要通过插入 page 样式的方法保证样式不会覆盖
const el = document.createElement('style');
el.type = 'text/css';
el.appendChild(document.createTextNode('@page { margin: 0mm; size: 80mm 160mm;}'));
document.head.appendChild(el);