Send a form with an uploaded file in HTTP request

Viewed 515

I have an email form and an input file. I would like to send it to my server but I can't upload the file correctly.

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);
      });
  }

I have no error in console but the file isn't in the mail. The attachment is File object.

I tried to use the formData but I don't understand the way it works because I need my object to be in the body or i'm missing something.

1 Answers

you have to use 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() 
Related