在 HTTP 请求中发送带有上传文件的表单

Send a form with an uploaded file in HTTP request

我有一个电子邮件表单和一个输入文件。我想将它发送到我的服务器,但我无法正确上传文件。

post(f: NgForm) {
    const email = f.value;
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.httpClient
      .post(
        environment.apiBaseUrl + 'usermail',
        {
          email: email.email,
          object: email.object,
          message: email.message,
          //the file to attach
          attach: email.attach,
        },
        { headers: headers }
      )
      .subscribe((response) => {
        console.log(response);
      });
  }

我在控制台中没有错误,但文件不在邮件中。附件是文件对象。

我尝试使用 formData 但我不明白它的工作方式,因为我需要我的对象在正文中或者我遗漏了一些东西。

你必须使用 multipart/form-data

 let formData = new FormData();
 formData.append("email", email.email);
 ...
 formData.append("attach", email.attach);


 this.httpClient
  .post(environment.apiBaseUrl + 'usermail', formData, { headers: headers }).subscribe()