当下载或者导出文件时,接口返回的数据又可能是一个后端的url
,这时候只需要直接在窗口打开就行了
window.location.href = res.fileUrl;
但是很多时候后端并不会讲数据存储为文件,而是返回一个文件流,这时候需要前端自己将文件流转换为文件,文件流转换为文件时需要这么几个注意点
- 请求头
'Content-Type': 'application/json'
- 返回值转为
blob
- 后端返回的文件名由于存在前后端跨域问题所以获取不到
response header
的Content-Disposition
属性,这时候服务端要设置header
Access-Control-Expose-Headers: Content-Disposition
后前端才能获取到Content-Disposition
const response = await fetch(
url + '?' + parseQuery(params),
{
method: 'GET',
headers: {
Authorization: `bearer ${cookieToken}`,
'Content-Type': 'application/json',
},
responseType: 'blob',
}
);
response.blob().then((res) => {
filename = response.headers.get('Content-Disposition') &&
decodeURI(response.headers.get('Content-Disposition'))
.split('filename=')[1]
.replaceAll('"', '');
const url = window.URL.createObjectURL(new Blob([res]));
const fileDownloader = document.createElement('a');
fileDownloader.href = url;
fileDownloader.download = filename;
fileDownloader.click();
});
- 如果返回值是个
Response
对象,则需要转换为Blob
对象
image.png
response.blob()
- 如果返回对象是个
Blob
对象,则可以直接转换
image.png