Angular:如何从HttpClient下载文件? [英] Angular: How to download a file from HttpClient?

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

问题描述

我需要从后端下载一个excel,它返回了一个文件.

I need download an excel from my backend, its returned a file.

我执行请求时收到错误消息:

When I do the request I get the error:

TypeError:您在期望流的位置提供了"undefined".你 可以提供一个Observable,Promise,Array或Iterable.

TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

我的代码是:

this.http.get(`${environment.apiUrl}/...`)
      .subscribe(response => this.downloadFile(response, "application/ms-excel"));

我尝试了get和map(...),但是没有用.

I tried get and map(...) but didn't work.

详细信息:角度5.2

参考:

import { HttpClient } from '@angular/common/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';

响应的内容类型:

Content-Type: application/ms-excel

怎么了?

推荐答案

尝试如下操作:

类型:application/ms-excel

type: application/ms-excel

/**
 *  used to get file from server
 */

this.http.get(`${environment.apiUrl}`,{
          responseType: 'arraybuffer',headers:headers} 
         ).subscribe(response => this.downLoadFile(response, "application/ms-excel"));


    /**
     * Method is use to download file.
     * @param data - Array Buffer data
     * @param type - type of the document.
     */
    downLoadFile(data: any, type: string) {
        let blob = new Blob([data], { type: type});
        let url = window.URL.createObjectURL(blob);
        let pwa = window.open(url);
        if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
            alert( 'Please disable your Pop-up blocker and try again.');
        }
    }

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

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