Angular 4.3 : Getting an arraybuffer with new HttpClient

标签 angular blob httpclient arraybuffer

我想换成新的 HttpClient。到目前为止,我处理以下文件下载:

getXlsx (): Observable<any> {
    return this.http.get('api/xlsx', {
      responseType: ResponseContentType.ArrayBuffer, // set as ArrayBuffer instead of Json
    })
    .map(res => downloadFile(res, 'application/xlsx', 'export.xlsx'))
    .catch(err => handleError(err));
  }

export function downloadFile(data: any, type: string, filename: string): string {
  const blob = new Blob([data._body], { type });
  const url = window.URL.createObjectURL(blob);

  // create hidden dom element (so it works in all browsers)
  const a = document.createElement('a');
  a.setAttribute('style', 'display:none;');
  document.body.appendChild(a);

  // create file, attach to hidden element and open hidden element
  a.href = url;
  a.download = filename;
  a.click();
  return url;
}

将 respondeType 更改为“arraybuffer”将导致空文件。有什么解决办法吗?

最佳答案

所以 Martin 解决了我的问题:

getXlsx (): Observable<any> {
    return this.http.get('api/xlsx', {
      responseType: 'blob' // <-- changed to blob
    })
    .map(res => downloadFile(res, 'application/xlsx', 'export.xlsx'))
    .catch(err => handleError(err));
  }

export function downloadFile(blob: any, type: string, filename: string): string {
  const url = window.URL.createObjectURL(blob); // <-- work with blob directly

  // create hidden dom element (so it works in all browsers)
  const a = document.createElement('a');
  a.setAttribute('style', 'display:none;');
  document.body.appendChild(a);

  // create file, attach to hidden element and open hidden element
  a.href = url;
  a.download = filename;
  a.click();
  return url;
}

关于 Angular 4.3 : Getting an arraybuffer with new HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46878484/

相关文章:

angular - 在 ag-Grid 中自定义 Material 主题不使用复选框的强调色

angular - 无法获取 Angular ng serve 命令以建立 https 上下文

node.js - npm 安装失败并出现错误

PHP MySQL : Saving PDF to Database

java - 将图像保存到 Google App Engine/Java 时出错

javascript - 在 Angular 5 的帮助下,选中复选框并将其存储在我的数据库中

mysql - 将 BLOB 从一台服务器复制到另一台服务器

android - Titanium,等待 HTTPClient 回复

java - 带有客户端证书身份验证的 HttpClient 后请求

android - 通过 HTTPS 连接到具有自签名证书 : "Trust anchor for certification path not found." 的站点的 Xamarin Android 问题