Angular 6:下载文件问题

4

我遇到了一个问题,但是无法找到任何解决方案。如果这个问题在某种程度上与其他人重复,请提前道歉。

问题是我向后端发送GET请求并收到响应。响应正文中有Blob。我试图下载它,但是在获取文件名以命名我的下载文件之前。在本地一切都很好。但在外部版本中,文件无法下载。我在单击按钮后获得响应,并看到我进入了FileUtil中的保存函数。但是下载没有开始。有没有人知道问题所在?

以下是Chrome检查工具中网络选项卡中的响应(如您所见,所有标题均已接收) enter image description here

download.service.ts

downloadFile(id: string) {
    return this.apiService.getFile(id).pipe(
        map(response => {
            const data = response.body;
            const blob = new Blob([data], { type: 'application/zip' });
            FileUtil.save(blob, this.getFileName(response.headers));
        })
    )
}

private getFileName(headers: HttpHeaders) {
    const contentDisposition = headers.get('Content-Disposition') || '';
    const matches = /filename=([^;]+)/ig.exec(contentDisposition);
    const fileName = (matches[1] || 'file.zip').trim();
    return fileName;
}

api.service.ts

getFile(id: string): Observable<HttpResponse<Blob>> {
    return this.httpClient.get<Blob>(requestUrl, {responseType: 'blob' as 'json', observe: 'response'});
}

FileUtil.ts

static save(data: Blob, name: string) {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(data);
    a.href = url;
    const filename = name;
    a.download = filename;
    a.click();
    setTimeout(() => {
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    }, 0);
}

可能是重复问题: https://stackoverflow.com/questions/53284400/download-a-file-using-angular-6-and-spring-rest-api/53285289#53285289 - Abdelkarim EL AMEL
2个回答

1
问题的原因是缺少 ('Access-Control-Expose-Headers', 'Content-Disposition'),浏览器不知道我的响应是应该下载的附件。因此,请仔细检查您的响应头两次。

0

你可以尝试这样做

FileUtil.ts

 save(data: Blob, name: string) {
   const a = document.createElement('a');
   document.body.appendChild(a);
   const blob = new Blob([data], { type: 'octet/stream' });
   const url = window.URL.createObjectURL(data);
   a.href = url;
   a.download = "filename.csv"; // you need to write the extension of file here
   a.click();
   window.URL.revokeObjectURL(url);
  })
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接