You would like to upload or post something not as an application/json
but as a multipart/formdata
.
It’s pretty simple, simpler than you would’ve thought 🙂
1. create the FormData instance
1 2 3 |
public JSON2FormData() { const fd = new FormData(); } |
then you can use .set or .append methods to add values to the post body of the FormData.
1 2 3 4 5 6 7 8 9 10 |
public JSON2FormData() { const fd = new FormData(); fd.set('greeting', 'hello there'); // upload a file, as in `File()` // let's assume our component has a `private file: File = new File()` fd.set('file', this.file, 'filename'); // or file.name instead of 'filename' // or you have an object that you'd like to send as a JSON object // let's assume out component has a `private myobject: object = {}` fd.set('myjson', JSON.stringify(this.myobject)); } |
and finally we upload it or send it away, rather.
1 2 3 4 |
// some service public uploadFormData(fd: FormData) { return this.http.post('/url', fd); } |
if we have a file upload and would like to be notified about upload progress
1 2 3 4 5 6 |
public uploadFormData(fd: FormData) { return this.http.post('/url', fd, { reportProgress: true, observe: 'events', }); } |
when we subscribe to this, we have several events happening.
1 2 3 4 5 6 7 8 |
this.formdataService.uploadFormData.subscribe(event => { switch (event.type) { case HttpEventType.UploadProgress: case HttpEventType.ResponseHeader: case HttpEventType.Response: // etc } }) |