【问题标题】:Return File from Web API in Angular 5从 Angular 5 中的 Web API 返回文件
【发布时间】:2019-01-17 15:44:08
【问题描述】:

我正在从 Web API 返回一个文件

 [HttpGet("[action]")]
    public FileResult DownloadExcel()
    {
        return File($"~/files/Input.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Input.xlsx");
    }

效果很好

现在我想在按钮单击时以角度使用它

所以我在网上找到了一些代码

downloadFile() {
return this.http.get(this.baseUrl + 'api/Common/DownloadExcel/', { responseType: 'blob' })
.map(res => {
  return {
    filename: 'filename.xlsx',
    data: res.blob()
  };
}).subscribe(res => {
  console.log('start download:',res);
  var url = window.URL.createObjectURL(res.data);
  var a = document.createElement('a');
  document.body.appendChild(a);
  a.setAttribute('style', 'display: none');
  a.href = url;
  a.download = res.filename;
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove(); // remove the element
}, error => {
  console.log('download error:', JSON.stringify(error));
}, () => {
  console.log('Completed file download.')
});

}

但是报错

类型“Blob”上不存在属性 Blob

在下面一行

 data: res.blob()

我已经导入了

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map'

我在这里缺少什么?这段代码对吗?

【问题讨论】:

    标签: angular .net-core asp.net-core-webapi


    【解决方案1】:

    试试这样的:

    服务电话:

    getUploadedFile(url:string){
            let headers = new HttpHeaders().append("Authorization", "Bearer " + token)
            return this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});
        }
    

    this.type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    在组件中:

        /**
         * Method is used to view or download the file
         */
        getFile() {
            this.uploadFileService.getUploadedFile(this.url).subscribe(respData => {
                this.downLoadFile(respData, this.type);
            }, error => {
    
            });
        }
    
    
        /**
         * Method is use to download file from server.
         * @param data - Array Buffer data
         * @param type - type of the document.
         */
        downLoadFile(data: any, type: string) {
            var blob = new Blob([data], { type: type.toString() });
            var url = window.URL.createObjectURL(blob);
            var pwa = window.open(url);
            if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
                alert('Please disable your Pop-up blocker and try again.');
            }
        }
    

    【讨论】:

    • 谢谢,有没有办法用这种方法设置文件名??
    • 这是一个很棒的简单示例,第一次使用 - 谢谢。
    • 哇,我和@theotherdy...第一次工作。谢谢!
    猜你喜欢
    • 2016-04-23
    • 2016-04-23
    • 2018-07-17
    • 2018-11-25
    • 2016-03-16
    • 2021-09-24
    • 2015-07-09
    • 2016-07-11
    • 2016-12-17
    相关资源
    最近更新 更多