平时开发中我们很多时候都会要用到文件下载,所以总结了一下平时常用得一些下载方法。
1、文件流二进制
// 在请求的时候加上getResponse 为true ,这样就可以得到头部信息,通过头部信息就可以拿到后台返回得文件名
/**
* @param {String} res 二进制流
* @param {String} name下载文件名称(可传可不传)
*/
export function use_flow_download(res: any, name?: string) {
if (!data) {
return;
}
let fileName = ""
const hs = res.headers.get('content-disposition');
if (hs) {
const reg = /filename=(.*)/;
fileName = name||reg.exec(hs)[1].trim();
}
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', `${fileName}`);
document.body.appendChild(link);
link.click();
}
2、通过 form 下载文件(支持post传参)
/**
* @param {String} method http method
* @param {String} action 后端接口
* @param {Object} params 请求参数
*/
export async function use_form_download(method: string, action: string, params: any = {}) {
const inputs = Object.keys(params)
.map((key) => {
return `<input type='hidden' name='${key}' value='${params[key]}'/>`;
})
.join('');
const $form = document.createElement('form');
$form.action = action;
$form.method = method;
$form.innerHTML = inputs;
document.body.appendChild($form);
$form.submit();
setTimeout(() => {
$form.remove();
}, 10000);
}
3、通过 iframe 下载文件
/**
* @param {String } download_path 需下载文件的链接
*/
export async function use_iframe_download(download_path: string) {
const $iframe = document.createElement('iframe');
$iframe.style.height = '0px';
$iframe.style.width = '0px';
document.body.appendChild($iframe);
$iframe.setAttribute('src', download_path);
setTimeout(() => {
$iframe.remove();
}, 20000);
}
4、通过 a标签下载文件
/**
* @param {String } download_path 需下载文件的链接
*/
export function use_a_download(download_path: string) {
const $a = document.createElement('a');
document.body.appendChild($a);
$a.href = download_path;
$a.download = 'download';
$a.click();
setTimeout(() => {
$a.remove();
}, 20000);
}
5、window.open下载文件
window.open('file/test.xls');
6、文件下载带参数
url = '/api/software-manager/download' + '?token=' + Token.get()