首页 > 解决方案 > 如何从api保存文件

问题描述

我是 Angular 新手,我需要知道如何将我的 API 中的文件保存在用户计算机上。在我的 API 中,我downloadChapter在 /download/chapter/{id} 上有带有方法的 DownloadController。当我从 Chrome 调用此方法时,我的计算机刚开始下载章节文件 - 没关系。当我从我的 DownloadService 中以角度调用此方法时,我在控制台中收到错误:ERROR OK。

我的下载章节方法:

  downloadChapter(id: number): Observable<Blob> {
    return this.http
      .get<Blob>(`${this.basicPath}/chapter/${id}`)
      .pipe(
        tap((res) => {
            console.log(`response: ${res}`);
          },
          (e) => {
            console.log(`error: ${e} - ???`);
          }, () => {
            console.log('win!');
          }),
      );
  }

在 API 响应中:

200 OK OK,URL [file:/Users/lukasz/Workspace/Inz/api/booky/uploads/1/6:Solaris%20-%20Maly%20Apokryf.mp3],[Content-Disposition:"attachment;filename=6 :Solaris%20-%20Maly%20Apokryf.mp3", Content-Type:"audio/mpeg", Content-Length:"97857000"]

如何解决?我只想将文件保存在用户计算机上。

标签: angularapifiledownload

解决方案


这是一个从 restful api 下载文件的 Angular 6 示例:

安装文件保护程序: npm install file-saver --save

import { HttpClient } from '@angular/common/http';
import { saveAs } from 'file-saver';

.
.
.
constructor(private http: HttpClient) { }

download() {
    this.http.get('/download/chapter/{id}', {responseType:'blob', observe: 'response'}).subscribe(
      (data : any)=>{
        saveAs(data.body, 'yourfilename.ext');
      },
      (err : HttpErrorResponse)=>{
        console.error('download failed:', err);
      });
}

.
.
.

推荐阅读