碰到一个大坑,附件文件存在华为云上,查询列表里记录的附件给了一个https开头的url,要求点击附件图标,下载附件到本地,
思路1.直接<a href='url' download='fileName' >下载</a>
实际效果:跨域下载不了,
思路2.接口调用url,然后返回的流通过window.URL.createObjectURL(blob)下载
const res = await get(url, params, { responseType: 'blob', });
console.info('----------------res-----', res)
if (res) {
const blob = new Blob([res], { type: 'application/pdf;charset=utf-8'});
let url2 = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.style.display = "none";
link.download = param.fileName;
link.href = url2;
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(link.href)
} else {
error();
}
---封装的get方法
const get = async (url, param = {}, header = {}) => {
try {
const response = await axios({
url: `${url}`,
method: "get",
params: param,
requestId: url,
timeout: 30000,
headers: header,
});
return response.data;
} catch (err) {
return {
isError: true,
statusCode: -10001,
message: "接口异常",
data: null,
};
}
};
结果打印日志,显示返回了乱码流文件,下载出的文件大小感觉没问题,但是打不开(报错),前端日志如下,
展示效果如下:
怎么检查感觉都没问题,这流文件明明都打印出来取到了,文件大小也跟上传的大小差不多,改了快一天,终于发现,是get方法有问题,看着返回的是流,其实不是Blob,修改如下
const getStream = async (url, param = {}, header = {}) => {
try {
const response = await axios({
url: `${url}`,
method: "get",
params: param,
requestId: url,
timeout: 30000,
responseType: 'blob',
headers: header,
});
return response.data;
} catch (err) {
return {
isError: true,
statusCode: -10001,
message: "接口异常",
data: null,
};
}
};
axios参数加了responseType: 'blob',如果不加默认是json,完美解决