好久没有写东西了,因为我换了一家公司但是,居然比之前还忙。之前有写过get的文件自动下载,今天记录一下post自动下载。
export async function downloadBlob() {
let res = await consts.axios.post(saveUrl, params, {
responseType: 'arraybuffer',
});
if (!res) return;
try {
//如果不报错,说明后台返回的是json对象,则弹框提示
//如果报错,说明返回的是文件流,进入catch,下载文件
let enc = new TextDecoder('utf-8');
res = JSON.parse(enc.decode(new Uint8Array(res.data))); //转化成json对象
if (res.code == '200') {
//操作成功,
});
} else {
//接口请求失败
}
} catch (err) {
const name = res.headers['content-disposition'].match(/filename="(S*)"|filename=(S*)/)
const fileName = decodeURIComponent(name[1] || name[2]);
downloadAttachment(res.data, fileName);
}
}
export function downloadAttachment(data, fileName) {
let fileContent = data;
let a = document.createElement('a');
a.download = fileName;
a.href = global.URL.createObjectURL(new Blob([fileContent]));
a.click();
}