通过Angular 2下载文件 [英] File download through Angular 2

查看:71
本文介绍了通过Angular 2下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个后端,我设置通过设置标题来返回文件

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

Content-Disposition: attachment;filename=somefile.csv

它直接在浏览器中工作,并在调用指向的URL时立即下载文件到那个资源。

It works directly in the browser and downloads the file immediately upon invoking the URL that points to that resource.

我的目标是在Angular 2模板中有一个按钮。当用户单击该按钮时,我需要从客户端收集一些数据(一些ID)并将其发送到服务器以调用该文件下载URL。

My goal is to have a button in an Angular 2 template. When the user clicks that button, I'd need to collect some data from the client-side (some IDs) and send it to the server to invoke that file download URL.

我希望用户保持同一页面并且没有打开任何新标签但只是让文件开始下载(就像直接调用URL一样)。

I'd like the user to stay on the same page and not have any new tabs open up but simply have the file start downloading (just like when the URL is invoked directly).

需要通过 POST请求来完成,因为我可以发送大量数据来确定需要下载哪些资源。

It will need to be done through a POST request because I can have quite a bit of data to send to identify what resource needs to be downloaded.

Angular 2方面的调用是什么样的?我试过了几件事,但我显然走错了路。

What does the call on the Angular 2 side look like for this? I tried a couple of things but I am obviously on the wrong path.

任何帮助都会受到赞赏!

Any help would be appreciated!

推荐答案

当我尝试下载我的节点服务器发送的PDF文件时,我遇到了类似的问题。我正在我的服务器上发出一个带有一些id细节的GET请求。
这对我有用。

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.

功能致电我的服务

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

服务

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

并且不要忘记导入ResponseContentType

And dont forget to import ResponseContentType

希望这可以帮助你

这篇关于通过Angular 2下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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