Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.7 can't parse POST multipart/form-data request

I use this code in Angular to send data to my Laravel 5.7 API endpoint as a multipart/form-data:

sendImageFile(id: number, fileToUpload: File) {
  const formData: FormData = new FormData();
  formData.append('file', fileToUpload, fileToUpload.name);
  formData.append('photoalbum_id', id.toString() );

  this.headers.delete('Content-Type'); // remove default application/json setting
  this.headers.append('Content-Type', 'multipart/form-data');

  this.options = new RequestOptions({ headers: this.headers });

  return this.http.post(this.url, formData, this.options)
    .pipe(catchError(this.handleError));
}

I checked the sent data with this code:

new Response(formData).text().then(console.log);

Get this result in console:

------WebKitFormBoundaryRjHGSmIZUd0iUMK9
Content-Disposition: form-data; name="file"; filename="mice.jpg"
Content-Type: image/jpeg

here-is-some-blob-data

------WebKitFormBoundaryRjHGSmIZUd0iUMK9
Content-Disposition: form-data; name="photoalbum_id"

1

So it seems the datas (and the photoalbum_id field) has been sent.

But the Laravel get back an Internal Server Error with this error message:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'photoalbum_id' cannot be null (SQL: insert into...

What do I wrong in this case? Why don't parse Laravel the form datas?

like image 664
netdjw Avatar asked Dec 05 '25 17:12

netdjw


1 Answers

The issue is Laravel's csrf protection. You need to add csrf_token to your formData

formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

or you can add to your post header

        headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},

also you need to add your http.post

    contentType: false,
    processData: false,

Here is the two related answer first , second

Hope it helps...

like image 111
Whatatimetobealive Avatar answered Dec 07 '25 15:12

Whatatimetobealive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!