问题:
后端在返回文件流时,将文件类型放在了响应头中,需要前端获取filename后手动添加文件名后缀。
代码:
前端:
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 (简单响应首部)可以暴露给外部:文章来源:https://www.toymoban.com/news/detail-689497.html
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
需要后端添加setHeader,将Content-disposition暴露出来以便前端访问获取。文章来源地址https://www.toymoban.com/news/detail-689497.html
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition")
response.setHeader("Content-Disposition", ...)
到了这里,关于前端如何获取响应头Content-Disposition中的filename的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!