File download through Angular 2

前端 未结 2 538
盖世英雄少女心
盖世英雄少女心 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:41

    i have implemented it like this.

    i have a service requesting file download. The response return a url, which is on amazon s3. This is a zip file containing what i want to download.

    the below works on all browsers.

    in your controller

    requestDownload() {
    
    this.downloadservice.downloadImages(obj)
          .subscribe(
            response => this.download(response )
          );
    
    }
    
    // res is an object
    download(res){ 
        var link = document.createElement("a");
        link.download = "a";
        link.href = res.link;
        document.body.appendChild(link);
        link.click();
    
         }
    

    downloadservice file

    downloadImages(body): Observable<any>{
    
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            return this.http.post("/Camera51Server/getZippedImages", body, options)
                .map((res:Response) => res.json())
                .catch(this.handleError);
        }
    

    if you like i can give you a link to the repository.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题