问题:
后端在返回文件流时,将文件类型放在了响应头中,需要前端获取filename后手动添加文件名后缀。
代码:
前端:
javascript">downloadFile(response, fileName) {
const headers = response.headers;
const contentType = headers['content-type'];
const blob = new Blob([response.data], { type: contentType });
const temp = response.headers['content-disposition'];
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
let matches = filenameRegex.exec(temp);
let fileType = '';
if (matches != null && matches[1]) {
fileType = matches['input'].substring(matches['input'].lastIndexOf('.'));
}
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = fileName + fileType; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}
后端:
header默认只有六种 simple response headers (简单响应首部)可以暴露给外部:
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
需要后端添加setHeader,将Content-disposition暴露出来以便前端访问获取。
response.setHeader("A***ess-Control-Expose-Headers", "Content-Disposition")
response.setHeader("Content-Disposition", ...)