【发布时间】:2021-01-04 20:18:13
【问题描述】:
我在后端有带有 spring boot 的 angular 7 应用程序,我将文件保存在资源文件夹中,并且下载它们时遇到了麻烦。 这是我的控制器:
@RequestMapping(value = "/getfile", method = RequestMethod.POST)
public void getFile(@RequestBody long id, HttpServletResponse response) {
try {
FileExpense fileExpense = fileExpenseRepo.findById(id).orElseThrow(() -> new CustomException(String.format("Договор (id:%s) не найден", id)));
if(fileExpense != null) {
File fileDownload = new File(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
response.setHeader("Content-Dispasition", "attachment; filename=" + fileExpense.getFileName());
response.setContentType("application/vnd.ms-excel");
OutputStream outputStream = response.getOutputStream();
Path path = Paths.get(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
response.setStatus(500);
}
}
和角度服务:
public getFile(id: number): Observable<any> {
return this.http.post('/expense/getfile', id);
}
以及组件中的下载功能:
downloadFile(fileJson: FileExpenseJson){
this.expenseService.getFile(fileJson.id).subscribe(data => {
let blob = new Blob([data.blob], {type: 'application/vnd.ms-excel'});
let url = window.URL.createObjectURL(blob);
let filename = fileJson.fileName;
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
let a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
window.URL.revokeObjectURL(url);
});
}
这给了我错误:消息:“位置 0 处 JSON 中的意外标记 P” 请帮忙 。无论如何,谢谢)
【问题讨论】:
-
我看到了这个问题,他们没有帮助我,我认为是前端下载过程中的整个问题
标签: angular typescript