【发布时间】:2020-06-12 13:08:02
【问题描述】:
祝您阅读本文愉快!
我在此软件设置中完成了上传功能,但我无法完成下载部分... 在这里尽可能多地挖掘,这就是我到目前为止的地方。
我的代码如下所示:
服务器
@GetMapping(value = "/projects/file/download/{filename}/{projectId}")
public ResponseEntity<byte[]> getResource(@PathVariable String filename, @PathVariable Long
projectId,HttpServletResponse response) throws ResourceNotFoundException, IOException {
String fileLocation=//a location that I set, removed logic to make this shorter
File downloadFile= new File(fileLocation);
byte[] isr = Files.readAllBytes(downloadFile.toPath());
String fileName = filename;
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(isr.length);
respHeaders.setContentType(new MediaType("text", "json"));
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);
}
角度服务
downloadFile(filename: string, projectId: number): Observable<any> {
return this.http.get(`${this.baseUrl}/file/download/` + filename + '/' + projectId, { responseType: 'blob' });
}
角度组件
downloadFile(fl: FileModel) {
//calling service
this.projectSerivce.downloadFile(fl.fileName, this.id).subscribe(response => {
window.open(response.url, '_blank');
});
}
它到达服务器并返回,然后打开一个新的空白浏览器选项卡,没有其他任何反应.. 没有任何错误。
【问题讨论】:
-
@michaeak 试过了,我得到另一个错误:SyntaxError: Unexpected token P in JSON at position 0
-
我修复了这个错误,但是当从服务器返回时,blob 是空的,并且 response.body 是未定义的
标签: angular spring-boot download