(angular 8) sending file data in $http Post data gives {} on rails API logs

165 Views Asked by At

angular 8, Rails 5.2 API

I am trying to attach an image to my Event model in edit form. I am following this tutorial

my typescript code:

const httpOptions = {
headers: new HttpHeaders({
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8; multipart/form-data',
    Authorization: environment.apiAuthKey,
  })
};
updateEvent(event: Event): Observable<Event> {
    return this.http.put<Event>(url, event, httpOptions)
    .pipe(
   ...
 }

This generates these logs on Rails API side:

Started PUT ...
Processing by ... as JSON
  Parameters: {"title"=>"testing image", "image" => {}}
...

Any idea why image param is being null?

So far, from my research I got an idea that I have to put multipart-formdata in my HTTP headers, I did that but no change in output.

1

There are 1 best solutions below

0
BELLIL On

Try to use formData instead of FormGroup

const formData = new FormData();

formData.append('image', image);
formData.append('title', testing image);
this.http.post(url, formData);

you can also do a test to post without setting HttpHeaders, FormData will set the suitable header for you