首页 > 解决方案 > Angular:使用 Angular HTTP 表单数据发送远程文件

问题描述

我的服务器端点上有一个文件可用http://xyz/file

我想使用 multipart/form-data 通过 HTTP POST 在 Angular 6 中发送这个文件。感谢这个相关的问题,这是我的方法:

    const filePath = 'http://xyz/file'
    const formData = new FormData();
    formData.append('file', filePath);

    this.http.post(endpoint, formData).subscribe(response => {
        console.log(response);
    });

问题是,如果我指定文件端点的文件路径而不是文件本身,这似乎不起作用。尝试此操作时,我在控制台中收到错误消息ERROR TypeError: "Argument 2 of FormData.append is not an object."

我该如何解决这个问题?我可以以某种方式使用远程文件进行 POST 吗?还是我需要先下载文件然后发送?我该怎么做?

标签: angularfilehttpmultipartform-data

解决方案


您不能只发送文件的链接。Formdata 字段期望具有文件内容。您可以分两步执行此操作

  1. 创建一个函数将远程文件下载到 Blob
  2. 通过 Post 请求发送 blob
fetch('https://some/file/here.png')
  .then(res => res.blob()) // Gets the response and returns it as a blob
  .then(blob => {
    var formData = new FormData();
    formData.append("file", blob);

    this.http.post(endpoint, formData).subscribe(response => {
        console.log(response);
    });

  });

推荐阅读