3

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?

netdjw
  • 5,419
  • 21
  • 88
  • 162

2 Answers2

2

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...

Whatatimetobealive
  • 1,353
  • 10
  • 15
  • 1
    Thanks for your answer, but I don't use `csrf_token`, I use JWT to authorization and the JWT token is already in the header. But the `contentType: false` (deleted Content-Type option from header was helped. Thank you! – netdjw Jan 06 '19 at 10:05
-3

seems photoalbum_id has been sent but you don't insert it to database into photoalbum_id column. fix the insert code and insert your data to photoalbum_id column OR if you sometimes don't want to insert data into that column, make this column nullable OR put your controller code to help better ..

behnam
  • 215
  • 1
  • 8
  • The SQL insert code is correct, tested in Postman, but the question is answered. Thank you! – netdjw Jan 06 '19 at 10:06