如何下载我的服务器(springboot)上生成的pdf角文件? [英] How to download a pdf file in angular which is generated on my server(springboot)?

查看:157
本文介绍了如何下载我的服务器(springboot)上生成的pdf角文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将从基于Spring的静态Web服务发送的.pdf文件下载到我的angular应用程序.如何下载它,我在我的angular应用程序或spring boot上缺少某些代码吗?"

"I want to download a .pdf file sent from spring-based restful web service to my angular app. How to download it, am I missing some code on my angular app or spring boot?"

我正在将来自Angular 6应用的HTTP GET请求发送到我的spring-boot服务器,该服务器会生成一个.pdf文件,然后将这个.pdf文件作为blob发送给我, 但是,当我尝试在有角度的一侧创建blob并打开pdf时,它显示以下错误:

I am sending an HTTP GET request from an angular 6 app to my spring-boot server, which generates a .pdf file and then sends me this .pdf file as a blob, but when I try to create a blob on my angular side and open the pdf, it shows the following error :

.错误错误:请求正文不是Blob或数组缓冲区

. ERROR Error: The request body isn't either a blob or an array buffer

我在StackOverflow上访问了以下问题,以找到一些解决方案: 1. PDF Blob未显示内容,Angular 2 2. 将HTTPResponse正文中的字节流转换为pdf文件 4. 使用SpringBoot将文件发送到Angular2

I have visited the following questions on StackOverflow, to find some solution: 1. PDF Blob is not showing content, Angular 2 2. How can I get access to the Angular 2 http response body without converting it to string or json? 3. converting byte stream in HTTPResponse body into a pdf file 4. Send File with SpringBoot to Angular2

在Angular应用中: 组件:

 
getPDF(){
      this.apiService.getPDF(this.invoiceId)
      .subscribe(
        (data) => {
          //data.blob() doesnt work properly
          var file = new Blob([data.blob()], { type: 'application/pdf' })
          var fileURL = URL.createObjectURL(file);
          window.open(fileURL); // if you want to open it in new tab
          var a         = document.createElement('a');
          a.href        = fileURL; 
          a.target      = '_blank';
          a.download    = 'bill.pdf';
          document.body.appendChild(a);
          a.click();
        },
        (error) => {
          console.log('getPDF error: ',error);
        }
      );
    }

服务:



    getPDF(invoiceId : number)
         {
             this.url = this.main_url + '/invoices/generatepdf/'+invoiceId;
             const headers = new Headers({ 'Content-Type': 'application/json', 
             "Authorization": authorization, responseType : 'blob'});
             return this.http.get(this.url, { headers : headers})
                 .pipe(map(
                     (response) => {
                         return response;
                     },
                     (error) => {
                         console.log(error.json());
                     }
                 ));
         }

在春季启动中:

控制器:



    @RestController
    @RequestMapping("/invoices")
    public class InvoiceController {

    @Autowired
        InvoiceService invoiceService;

    @GetMapping(path = "/generatepdf/{invoiceId}")
        public void generateInvoicePdf(@PathVariable Integer invoiceId,
                HttpServletRequest request,HttpServletResponse response) {
            invoiceService.generateInvoicePdf(invoiceId, request, response);
    }

ServiceImplementation:



    @Override
        public String generateInvoicePdf(Integer invoiceId, HttpServletRequest request, HttpServletResponse response) {

             //createPDF() will create a .pdf file
            createPDF(pdfFilename, dto, dtoForSupplier);
            if (pdfFilename != null) {
                try {
                    File file = new File(pdfFilename);
                    FileInputStream is = new FileInputStream(file);
                    response.setContentType("application/blob");

                    // Response header
                    response.setHeader("Pragma", "public");
                    response.setHeader("responseType", "blob");
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + pdfFilename + "\"");

                    // Read from the file and write into the response
                    OutputStream os = response.getOutputStream();
                    System.out.println(os);
                    byte[] buffer = new byte[(int) file.length()];

                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        os.write(buffer, 0, len);
                    }

                    System.out.println(os);
                    os.flush();
                    os.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return pdfFilename;
        }

我希望在浏览器中下载一个.pdf文件并打开它并查看其内容,但我收到了错误消息:

I expect to download a .pdf file in the browser and open it and see its contents, but instead i get the error:

core.js:15724错误错误:请求正文既不是Blob也不是数组缓冲区 在Response.push ../node_modules/@angular/http/fesm5/http.js.Body.blob(http.js:782) 在SafeSubscriber._next(invoice-details.component.ts:212) 在SafeSubscriber.push ../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber .__ tryOrUnsub(Subscriber.js:196) 在SafeSubscriber.push ../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next(Subscriber.js:134) 在Subscriber.push ../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next(Subscriber.js:77) 在Subscriber.push ../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next(Subscriber.js:54) 在MapSubscriber.push ../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next(map.js:41) 在MapSubscriber.push ../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next(Subscriber.js:54) 在XMLHttpRequest.onLoad(http.js:1070) 在ZoneDelegate.push ../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask(zone.js:423)>

core.js:15724 ERROR Error: The request body isn't either a blob or an array buffer at Response.push../node_modules/@angular/http/fesm5/http.js.Body.blob (http.js:782) at SafeSubscriber._next (invoice-details.component.ts:212) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:134) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at XMLHttpRequest.onLoad (http.js:1070) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)>

推荐答案

按照@JBNizet的建议,我实现了以下可观察对象:

As suggested by @JBNizet , I have implemented the observable as follows:

组件:

getPDF(){
      this.apiService.getPDF(this.invoiceId)
      .subscribe(
        (data: Blob) => {
          var file = new Blob([data], { type: 'application/pdf' })
          var fileURL = URL.createObjectURL(file);

// if you want to open PDF in new tab
          window.open(fileURL); 
          var a         = document.createElement('a');
          a.href        = fileURL; 
          a.target      = '_blank';
          a.download    = 'bill.pdf';
          document.body.appendChild(a);
          a.click();
        },
        (error) => {
          console.log('getPDF error: ',error);
        }
      );
    }

服务:

getPDF(invoiceId : number): Observable<Blob>
     {
         this.url = this.main_url + '/invoices/generatepdf/'+invoiceId;
         var authorization = 'Bearer '+sessionStorage.getItem("access_token");

         const headers = new HttpHeaders({ 'Content-Type': 'application/json',
         "Authorization": authorization, responseType : 'blob'});

         return this.httpClient.get<Blob>(this.url, { headers : headers,responseType : 
         'blob' as 'json'});
     }

我引用的

URL:

  1. 重载#2: https://angular.io/api/common/http/HttpClient#get
  2. 使用Http Post预览Blob: https://dzone.com/article/how-to-preview-blobs-with-http-post-and-angular-5
  1. Overload #2: https://angular.io/api/common/http/HttpClient#get
  2. Preview Blob with Http Post: https://dzone.com/articles/how-to-preview-blobs-with-http-post-and-angular-5

这篇关于如何下载我的服务器(springboot)上生成的pdf角文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆