【发布时间】:2019-02-04 17:41:06
【问题描述】:
我正在尝试使用 Angular 7 开发文件下载。我正在使用 HttpClient 和 FileSaver 进行下载。我遇到的问题是,当 HttpClient 向服务器发出下载请求时,它会等待整个响应完成(将整个文件保存在浏览器内存中)并且 save dialogue 仅出现在末尾。我相信在大文件的情况下,将其存储在内存中会导致问题。有没有一种方法可以在收到状态 OK 后立即显示 save dialogue 并将文件流式传输到文件系统。我还需要将授权标头与请求一起发送。
我的服务器端代码:
@RequestMapping(value = "/file/download", method = RequestMethod.GET)
public void downloadReport(@RequestParam("reportId") Integer reportId, HttpServletResponse response) throws IOException {
if (null != reportId) {
JobHandler handler = jobHandlerFactory.getJobHandler(reportId);
InputStream inStream = handler.getReportInputStream();
response.setContentType(handler.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=" + handler.getReportName());
FileCopyUtils.copy(inStream, response.getOutputStream());
}
}
我的客户代码(角度)
downloadLinksByAction(id, param) {
this._httpClient.get(AppUrl.DOWNLOAD, { params: param, responseType: 'blob', observe: 'response' }).subscribe((response: any) => {
const dataType = response.type;
const filename = this.getFileNameFromResponseContentDisposition(response);
const binaryData = [];
binaryData.push(response.body);
const blob = new Blob(binaryData, { type: dataType });
saveAs(blob, filename);
}, err => {
console.log('Error while downloading');
});
}
getFileNameFromResponseContentDisposition = (res: Response) => {
const contentDisposition = res.headers.get('content-disposition') || '';
const matches = /filename=([^;]+)/ig.exec(contentDisposition);
return matches && matches.length > 1 ? matches[1] : 'untitled';
};
【问题讨论】:
标签: angular download filesaver.js