1

Is there a way to send FormData and a json object at the same time in http.request of angular 2+? I need the solution for angular2+, not to angularjs.

let data = {id: 1, name: 'test'};
let formData = new FormData();
formData.append('fileData', file); //file from inputfile

let headers = new Headers();
headers.append('Accept', 'application/json');

let options =  new RequestOptions({ headers: headers });
options.method = 'POST';
options.body = data; //data is my object

//options.formData= formData; //formData is my FormData with file data to upload

this.http.request(url, options);
Ricardo Carvalho
  • 223
  • 5
  • 14
  • 1
    I finally found a proper way to upload a file and send some JSON within the same request and made a proper answer here: https://stackoverflow.com/questions/39693966/how-to-angular2-post-json-data-and-files-in-same-request/47408232#47408232 – maxime1992 Nov 21 '17 at 08:16

1 Answers1

3

You have to pass the file and the JSON object on the "formData" object like this example:

public submitForm(picture: File, data: any): Observable<any> {
 const formData = new FormData();
 formData.append('picture', picture);
 formData.append('data', JSON.stringify(data));
}
Cristian Zumelzu
  • 842
  • 10
  • 15