File download through Angular 2

前端 未结 2 537
盖世英雄少女心
盖世英雄少女心 2021-02-14 04:57

I have a backend that I set up to return a file through setting the header

Content-Disposition: attachment;filename=somefile.csv

It works direc

2条回答
  •  情歌与酒
    2021-02-14 05:50

    I had a similar issue when i was trying to download a PDF file which my Node server was sending. I was making a GET request on my server with some id details. This is what worked for me.

    Function Calling my service

    printBill(receiptID) {
    this.BillingService.printBill(receiptID)
        .subscribe(res => {
            saveAs(res,"InvoiceNo"+receiptID+".pdf");
            let fileURL = URL.createObjectURL(res);
            window.open(fileURL);
        })
    }
    

    Service

    printBill(billID) {
        return this.http.get('/billing/receipt/'+billID, 
                       { responseType: ResponseContentType.Blob })
          .map((res) => {
                return new Blob([res.blob()], { type: 'application/pdf' })
            })
    }
    

    And dont forget to import ResponseContentType

    Hope this helps you

提交回复
热议问题