问题:
后端在返回文件流时,将文件类型放在了响应头中,需要前端获取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 (简单响应首部)可以暴露给外部:
Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma需要后端添加setHeader,将Content-disposition暴露出来以便前端访问获取。
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition")response.setHeader("Content-Disposition", ...)