In a js web project, I want to POST a form with a complexe json schema, and in which some field will be file.
How do I do It?
I currently upload a file alone like this
const data = new FormData();
data.append('mimetype', file.type);
data.append('filename', file.name);
data.append('file', file);
return this.httpClient.post(url, data)
but I want my new form look like this:
var data ={username:"John doe",
profilPhoto:{mimetype:..., filename:..., file: ...},
house:{
photo:{mimetype:..., filename:..., file: ...},
},
documents:[{mimetype:..., filename:..., file: ...}]
}
As suggested in the comments encode your file to base64 then decode on the backend and save it as a blob. Another option would be to use FormData as you do. For the array of objects, you can use JSON.stringify and then JSON.parse on backend.
addFile(data:any): Observable<any> {
const postData=new FormData();
postData.append('username', data.username);
postData.append('profilPhoto', data.profilePhotoFile);
postData.append('house', data.houseFiles);
postData.append('documents', JSON.stringify(data.documents);
let API_URL = this.endpoint+`/add-file`;
return this.http.post(API_URL, postData)
}