【问题标题】:Angular 2 save file from Nodejs来自Nodejs的Angular 2保存文件
【发布时间】:2019-04-02 16:59:51
【问题描述】:

我在 NodeJS 中截取了代码以尝试从我的服务器下载。

router.post("/download", function(req, res, next) {
  console.log(req);
  filepath = path.join(__dirname, "/files") + "/" + req.body.filename;
  console.log(filepath);
  res.sendFile(filepath);
});

这是我的 Angular 2 代码: Component.ts

  download(index) {
    var filename = this.attachmentList[index].uploadname;
    this._uploadService
      .downloadFile(filename)
      .subscribe(data => saveAs(data, filename), error => console.log(error));
  }

Service.ts

export class UploadService {
  constructor(private http: HttpClient, private loginService: LoginService) {}
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      responseType: "blob"
    })
  };

  downloadFile(file: string): Observable<Blob> {
    var body = { filename: file };
    console.log(body);
    return this.http.post<Blob>(
      "http://localhost:8080/download",
      body,
      this.httpOptions
    );
  }

在我的 HTML 响应中,我将文件正确记录到浏览器的网络检查工具中。然而 Angular 正在尝试将响应解析为 JSON 对象,这显然不起作用,因为响应是一个 blob。

我得到的错误是这样的:

JSON.parse() 中位置 0 处的 JSON 中的意外标记 % 在 XMLHttpRequest.onLoad 角度 2

有人对此有解决方案吗?

提前致谢!

【问题讨论】:

  • 您已将responseType 添加为标头,但不应如此。它应该只是在httpOptions 对象内,而不是headers 对象内
  • @user184994 它在开始时工作,但是当我重新编译时它给了我一个编译错误。 “ src/app/services/upload.service.ts(25,7) 中的错误:错误 TS2345:类型为 '{ headers: HttpHeaders; responseType: string; }' 的参数不可分配给类型为 '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'。属性 'responseType' 的类型不兼容。类型 'string' 不可分配给输入'"json"'。"

标签: node.js angular http


【解决方案1】:

尝试以下 http 选项:

{
    responseType: 'blob',
    observe:'response'
}

然后您将收到HttpResponse&lt;Blob&gt; 类型的响应,因此在您的服务中执行 data.body 将为您提供可以传递给 saveAs 的 blob。

您可以在此处找到有关观察的更多信息:

https://angular.io/guide/http#reading-the-full-response

【讨论】:

    【解决方案2】:

    我解决了这个问题,在服务代码中我删除了帖子之后的内容,因为它强制我返回一个二进制文件,而不是 JSON。现在的代码是这样的:

      downloadFile(file: string): Observable<Blob> {
        var body = { filename: file };
        console.log(body);
        return this.http.post<Blob>(
          "http://localhost:8080/download",
          body,
          this.httpOptions
        );
      }
    

    谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2019-09-15
      • 2016-04-25
      • 1970-01-01
      • 2016-09-03
      • 2018-01-07
      • 2019-08-02
      相关资源
      最近更新 更多