Angular 从URL下载到计算机

Angular 从URL下载到计算机,angular,typescript,Angular,Typescript,我有一个服务器,我从服务器发送一个请求(ID)作为响应,我得到一个json,在json中我有一个字段ImagePath,带有指向图像的url。我怎样才能下载这张照片 html 服务 downloadImage(applicationId:number) { return this.http.get('http://192.168.0.138/api/GetPhoto?applicationId='+applicationId,{headers:this.headers})

我有一个服务器,我从服务器发送一个请求(ID)作为响应,我得到一个json,在json中我有一个字段ImagePath,带有指向图像的url。我怎样才能下载这张照片

html

服务

downloadImage(applicationId:number)
{
         return this.http.get('http://192.168.0.138/api/GetPhoto?applicationId='+applicationId,{headers:this.headers})
                         .map((res:Response)=> res.json() as DownloadImage
                        );

}
downloadImage(applicationId:number) {
    const _self = this;
    return this.http.get(`http://192.168.0.138/api/GetPhoto?applicationId=${applicationId}`, {headers:this.headers})
       .map((res:Response) => res.json() as DownloadImage)
       .toPromise()
       .then(function(dlImage: DownloadImage) {
          // Launch second call to dlImage.ImagePath
          const options = new RequestOptions({headers: myHeaderObj});
          return _self.http.get(dlImage.ImagePath, options);
        });
  }
JSON


只需尝试使用具有下载属性的常规html锚定标记:)

注意:根据控制器中变量的名称替换“response.ImagePath”

<a [href]="response.ImagePath" download="download.jpg"><i class="fa fa-download"></i> Download</a>


希望这有帮助。

要链接请求,您可以将
可观察的
转换为
承诺
,然后对其调用
。然后()
,这将获得上一次调用的映射结果作为参数。我不打算在angular2中添加下载文件的代码,因为它已经在十几篇文章中反复得到了回答

服务

downloadImage(applicationId:number)
{
         return this.http.get('http://192.168.0.138/api/GetPhoto?applicationId='+applicationId,{headers:this.headers})
                         .map((res:Response)=> res.json() as DownloadImage
                        );

}
downloadImage(applicationId:number) {
    const _self = this;
    return this.http.get(`http://192.168.0.138/api/GetPhoto?applicationId=${applicationId}`, {headers:this.headers})
       .map((res:Response) => res.json() as DownloadImage)
       .toPromise()
       .then(function(dlImage: DownloadImage) {
          // Launch second call to dlImage.ImagePath
          const options = new RequestOptions({headers: myHeaderObj});
          return _self.http.get(dlImage.ImagePath, options);
        });
  }
组成部分

 DownloadImage(applicationId:number)
    {
        var ID=applicationId;
        this.httpService.downloadImage(ID).subscribe((response)=>{
            console.log(response);
        })


    }
DownloadImage(applicationId:number) {
    this.httpService.downloadImage(applicationId).subscribe(resp => {
          // ... See numerous other SO topics for examples
    });
}

只需确保图片来自同一个域,否则您将遇到CORS问题(但这也已在十几篇SO帖子中得到解决)。

谢谢您的建议。但我需要这样做,以便根据来自服务器的链接发送和下载请求文件。有可能这样做吗?您可以使用以下方法之一:通过将数据转换为blob,但是您必须下载文件,而不是URL。或者使用一个小技巧:1。使用(单击)呼叫,因为您已经这样做了。2.得到答案3。触发我在第一个anwser中发布的href隐藏按钮的单击事件。