#How to post an image to an api

9 messages · Page 1 of 1 (latest)

sudden pasture
#

Hello devs,
I have this form roomForm = new FormGroup({ title: new FormControl(), price: new FormControl(), guestNumber: new FormControl(), details: new FormControl(), hotelId: new FormControl(), image: new FormControl(''), fileSource: new FormControl() }); and can upload upload like this ```onSelect(event: any) {
if (event.target.files.length > 0) {
this.file = event.target.files[0];

}

}

onSubmit() {
this.roomForm.patchValue({hotelId: this.hotelId})
this.roomForm.patchValue({
fileSource: this.file
})
this.apiService.addRoom(this.roomForm.value)
.subscribe((data) =>
console.log(this.roomForm.value)
)
}```
My problem is only the image information is posted to the endpoint and the actual file isn't.

tame raft
#

New FormData and append the file

sudden pasture
#

thank you @tame raft

#

append could not work with me I don't know why.
I had to send a base64 encoded string and decoded and transformed it to an image.

tame raft
#
 const formData = new FormData();
    for (const file of this.files) {
      formData.append('files', file);
    }
#

if you send multiple files

#
 const target = $event.target as HTMLInputElement;
 const file = target.files[0];
 const formData = new FormData();
 formData.append('file', file);

for single file

sudden pasture
#

Thank you @tame raft