gpt4 book ai didi

java - Angular 2 : PDF file download

转载 作者:太空宇宙 更新时间:2023-11-04 11:22:50 25 4
gpt4 key购买 nike

我正在尝试使用 Java-Angular 2 下载 PDF 文件。我已经使用 Postman 测试了我的 Java 代码,它工作得很好,但是当我在客户端接收数据时,我得到了:

Received data

如果我使用FileSaver,我会得到一个空文件。

这是 Java Controller 代码:

    @RequestMapping(value = { "/gestionnaire/documents/file/{id}" }, method = RequestMethod.GET, 
produces = {"image/jpeg","image/png", "application/json" , "text/plain" , "application/pdf"})
public ResponseEntity<InputStreamResource> getFile(HttpServletRequest request , @PathVariable Long id) throws JSONException, IOException {
Document document = documentService.findById(id);
File file = new File(document.getChemin());
String fileName = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("\\")+1);
InputStream input = new FileInputStream(file);
HttpHeaders headers = new HttpHeaders();
String extension = fileName.substring(fileName.lastIndexOf(".")+1);
switch (extension) {
case "pdf": headers.setContentType(MediaType.parseMediaType("application/pdf "));
break;
case "txt": headers.setContentType(MediaType.parseMediaType("text/plain "));
break;
case "png": headers.setContentType(MediaType.parseMediaType("image/png "));
break;
case "jpeg": headers.setContentType(MediaType.parseMediaType("image/jpeg "));
break;

default: headers.setContentType(MediaType.parseMediaType(""));
break;
}
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "GET, POST, PUT");
headers.add("Access-Control-Allow-Headers", "Content-Type");
headers.add("Content-Disposition",
"attachment;filename=\""+URLEncoder.encode(fileName, "UTF-8") + "\"
");
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.setContentLength(file.length());
ResponseEntity<InputStreamResource> response = new
ResponseEntity<InputStreamResource>(
new InputStreamResource(input), headers, HttpStatus.OK);
return response;
}

这是组件方法:

     openPopup(document : Document , size : string, title : string) {
this.documentService.getDocumentFile(document)
.toPromise().then((response : any) =>
{
let parts = document.chemin.split(".") ;

if(parts[parts.length -1] === "txt"){
var file = new Blob([response.text()], {type:
'text/plain;charset=utf-8'});
FileSaver.saveAs(file, 'fileDowloaded');
this.popup.open(NguiMessagePopupComponent, {
classNames: size,//large , medium , small
title: title,
message: response.text(),
buttons: {
OK: () => {
this.message = "Ok button is pressed";
},
CANCEL: () => {
this.message = "Cancel button is pressed";
this.popup.close();}
} });
}
if(parts[parts.length -1] === "pdf"){
var file = new Blob([response.arrayBuffer()], {type:
'application/pdf;charset=UTF-8'});
FileSaver.saveAs(file, 'fileDowloaded');
this.popup.open(NguiMessagePopupComponent, {
classNames: size,
title: title,
message: response.text(),
buttons: {
OK: () => {
this.message = "Ok button is pressed";
},
CANCEL: () => {
this.message = "Cancel button is pressed";
this.popup.close();}
} });
}

}
).catch(err=>"can't download file");

}

这是服务方法:

    getDocumentFile(document : Document){
let headers = new Headers();
let responseType : ResponseContentType.ArrayBuffer ;
let options = new RequestOptions({ headers : headers ,withCredentials:
true , responseType});
return this.http.get(super.getBaseUrl()
+"gestionnaire/documents/file/"+document.id,options)
}

我使用了 response.blob() 而不是 response.arrayBuffer(),但它仍然无法正常工作。

最佳答案

我遇到了类似的问题,我已经解决了:

为我服务

private options = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/pdf' })  , responseType : ResponseContentType.ArrayBuffer });
...
generatePDF( idJour: number): any {

return this.http.get(`${this.resourceUrl}/presenceCantinePDF/${idJour}`, this.options
).map((res: any) => {
return res;
});
}

我称之为:

generatePDF() {
this.presenceSyntheseService.generatePDF(774).subscribe((res) => {
console.log(res);
const blob = new Blob([res._body], { type: 'application/pdf' });
// window.open(URL.createObjectURL(blob));
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, 'testss.pdf');
} else {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'response.pdf';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
});
}

我的Java代码:

 @GetMapping(value = "/presence-synthese/presenceCantinePDF/{idJour}", produces = MediaType.APPLICATION_PDF_VALUE)
public @ResponseBody ResponseEntity<InputStreamResource> getPDF(@PathVariable Long idJour) throws IOException {
ByteArrayInputStream stream = presenceSyntheseService.generatePDF(idJour);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "inline; filename=presenceCantine.pdf");
//headers.add("Content-Disposition", "attachment; filename=ismael.pdf");
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(stream));

}

祝你好运

关于java - Angular 2 : PDF file download,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44724076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com