前端下载文件,js下载文件,axios使用post下载文件,post下载文件,流文件下载,下载文件
普通下载
在H5中,a标签新增了download 属性,包含该属性的链接被点击时,浏览器会以下载文件方式下载 href 属性上的链接。
<a href="http://aa.xlsx" download="http://aa.xlsx">下载</a>
// 或者封装
function download(href, title) {
const a = document.createElement('a');
a.setAttribute('href', href);
a.setAttribute('download', title);
a.click();
}
download('http://aa.xlsx', 'aa')
window.location.href 直接打开
window.location.href === 'http://aa.xlsx'
axios使用post下载文件
当后端返回的文件是流文件时
首先应在请求中设置返回类型:responseType: "blob"
import axios from 'axios';
axios(url, {
method: 'POST',
data: data,
responseType: 'blob', // 代表内存之中的一段为二进制
}).then((res) => {
const blob = res.data;
let link = document.createElement('a');
link.href = URL.createObjectURL(
new Blob([blob], { type: 'application/vnd.ms-excel' })
);
link.download = fileName;
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
});
流文件下载
当后端返回的文件是流文件时
首先应在请求中设置返回类型:responseType: "blob"
export const downLoad = (url, fileName) =>
request(url, {
method: "POST",
data: data,
responseType: "blob", // 代表内存之中的一段为二进制
}).then(data) => {
const blob = data;
let link = document.createElement("a");
link.href = URL.createObjectURL( new Blob([blob], { type: "application/vnd.ms-excel" }) );
link.download = fileName;
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
};
自定义文件名
downLoad('http://aa.xlsx', 'aa.xlsx')