Angular 2:PDF文件下载

时间:2017-06-23 14:37:18

标签: java angular

我正在尝试使用Java-Angular 2下载PDF文件。我已经使用Postman测试了我的Java代码并且它运行良好但是当我在客户端收到数据时,我得到了这个:< / p>

Received data

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

这是Java控制器代码:

    @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(),但它仍无效。

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,我已经解决了这个问题:

在我的服务中

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));

     }
祝你好运