我正在尝试通过单击 Angular 中的按钮来下载文件。文件已下载,但大小为 0 KB,无法打开。
这是我迄今为止在 Angular 和 Spring MVC 中使用的代码
Angular :
public downloadFile(fileName:string){
console.log("ready to download");
let param:any = {'messageId':this.loadedMessageService.messageId, 'attachmentName':fileName}
this.http.get(`https://fakeurl.com/abc/getFile`,{params:param,responseType:'blob'}).subscribe(
(data) => {
let b:Blob = new Blob([data])
//,{type: 'application/octet-stream',}
// const fileName :string= "RL.xlsx"
var url = window.URL.createObjectURL(b);
const a : HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
// const a = document.createElement('a');
document.body.appendChild(a);
a.href = url;
a.download = fileName;
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
)
}
Spring MVC:
@GetMapping(value = "/getFile")
public @ResponseBody byte[] getFile() throws IOException {
try {
return messageAttachmentService.getFile(Integer.parseInt(request.getParameter("messageId")), request.getParameter("attachmentName"));
} catch (NumberFormatException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.error(sw.toString());
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.error(sw.toString());
}
return null;
}
现在,当我单击按钮时,文件会被下载,但大小为 0 KB 并且无法打开。我之前使用类型为 application/octet-stream,因为要下载的文件可以是 PDF、文本文件或 xls。 我也提到了其他问题,并尝试将响应类型更改为 arraybuffer。这也没有解决问题。我的代码有什么问题吗?
最佳答案
您可以尝试使用 file-saver包裹。它很容易使用。
从“file-saver”导入*作为FileSaver;
const blob: any = new Blob([data], { type: 'octet/stream' });
saveAs(blob, "hello world.txt");
关于angular - 从 Angular 和 Spring MVC API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124360/