我遇到了使用angular2从弹簧启动下载文件的问题。
这是我春季启动的代码,它来自:Return generated pdf using spring MVC。我可以用邮差直接下载文件但不能用angular2 ...
@RequestMapping(value="/file/{id}", method=RequestMethod.GET)
public ResponseEntity<?> getFile(@PathVariable("id") long id) {
UploadFile uFile = uploadFileService.getUploadFileById(id);
byte[] contents = uFile.getContent();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.setContentDispositionFormData(uFile.getName(), uFile.getName());
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
}
Angular2服务
downloadFile( id: number ){
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
headers.append('Authorization',this.auth.token);
let options = new RequestOptions( { headers: headers, responseType: ResponseContentType.Blob});
return this.http.get(this.editUrl + id, options)
.map(res => {return new Blob([res.blob()],{ type: 'application/pdf' })});
}
并下载按钮
downloadFile(uFile: UploadFile){
this.uploadFileService.downloadFile(uFile.id)
.subscribe(
data => window.open(URL.createObjectURL(data)),
);
return false;
}
当我点击下载按钮时,chrome会打开新标签并立即关闭它而不显示任何文件。 以下是邮递员的一些回复标题。
Access-Control-Allow-Headers →Content-Type, x-requested-with, Authorization, responseType
Access-Control-Allow-Methods →POST, PUT, GET, PATCH, OPTIONS, DELETE
Access-Control-Allow-Origin →http://localhost:4200
Access-Control-Max-Age →3600
Cache-Control →must-revalidate, post-check=0, pre-check=0
Content-Disposition →form-data; name="reference.pdf"; filename="reference.pdf"
Content-Length →31576
Content-Type →application/pdf
Date →Mon, 27 Mar 2017 08:39:24 GMT
X-Content-Type-Options →nosniff
X-Frame-Options →DENY
X-XSS-Protection →1; mode=block
答案 0 :(得分:0)
Spring启动解决方案基于Return generated pdf using spring MVC和PDF Blob is not showing content, Angular 2上的Angular2。有问题的代码完全正常运行。 使用pdf文件自动关闭标签的原因是Chrome中的Adblock插件。