【问题标题】:Angular 4 HttpModule How to Return a File From Get RequestAngular 4 HttpModule 如何从获取请求中返回文件
【发布时间】:2018-01-05 11:22:12
【问题描述】:

我有一个 REST API,如果我直接在浏览器中查询,它会返回一个 JSON 或 CSV 文件以供下载。我想用 Angular HttpModule 做同样的事情。

我的 get 请求很简单(它有一个查询字符串参数来指示要返回的文件格式):

public Submit(request: Request) {
  ...
  return this.http.get(url).subscribe(response => {
    //What here
  });
}

响应内容类型为application/octet-stream。我已经尝试将响应作为 blob 处理,但这是行不通的。我怎样才能将服务器的响应传递给浏览器并让它下载文件?此方法是响应按钮单击的组件调用的服务的一部分

onClick() {
    this._requestService.Submit(request); //This gets the Subscription response from the service, but I want it to let the broswer download the file
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    你必须添加

    { responseType: ResponseContentType.Blob }
    

    然后将响应映射到 blob。

    return this.http.get(url, { responseType: ResponseContentType.Blob })
        .map(r => r.blob())
        .subscribe(response => {
    
        });
    

    接下来您可以使用 fileSaver.js 下载此文件。

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

      this.http.get(url).subscribe(response => {
        const blob = new Blob([response], { type: 'text/csv' });
        const url= window.URL.createObjectURL(blob);
        window.open(url);
      });
      

      【讨论】:

      • 试过了,报错:Resource 'blob:6BB5A3D5-0D0D-4537-B4F3-888D7A70DE57' not allowed to load.
      【解决方案3】:

      我从AngularJS $http-post - convert binary to excel file and downloadAngularJS: Display blob (.pdf) in an angular app 获得了大部分解决方案。

      let ieEDGE = navigator.userAgent.match(/Edge/g);
      let ie = navigator.userAgent.match(/.NET/g); // IE 11+
      let oldIE = navigator.userAgent.match(/MSIE/g); 
      
      let blob = new Blob([response.text()], { type: "application/octet-stream"});
      let fileName: string = "myfile." + this.request.output;
      
      if (ie || oldIE || ieEDGE) {
        window.navigator.msSaveBlob(blob, fileName);
      }
      else {
        let link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click(); 
      
        setTimeout(function () {
          window.URL.revokeObjectURL(url);
        }, 0);
      }
      

      对于非IE浏览器(“else”语句),我也能成功使用

      let reader = new FileReader();
      reader.onloadend = function () {
        window.location.href = reader.result;
      };
      
      reader.readAsDataURL(blob);
      

      对于第二种方法,重要的是 blob 类型为application/octet-stream,否则对于application/jsontext/csv 之类的,它将在新窗口/选项卡中打开文件。缺点是您无法提供文件名或扩展名,因此您会得到一个名为“下载”的原始文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 2018-04-17
        • 1970-01-01
        • 2012-03-30
        • 1970-01-01
        相关资源
        最近更新 更多