skip to Main Content

Im trying to upload a image from angular

onImageCahnge(event: any): void {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.herosliderForm.patchValue({
        imageSource: file
      });
    }
  }

on submit

const formData = new FormData();
formData.append('image', this.herosliderForm.get('image')?.value)

this.herosliderService.update(this.herosliderForm.value.id, formData).subscribe({
  next: (response: any) => {
    console.log(response)
  },
  error: (response: any) =>{
    console.log(response); //TODO
  }
})

In the function herosliderService.update()

update(id: number, data:  FormData):  Observable<Object>{

    data.forEach( (value: any ) => {
      console.log('update, value) //DEBUG

    })

    let headers: HttpHeaders = new HttpHeaders({
      'Authorization': `Bearer ${this.userService.getAccessToken()}`
    })

    return this.http.post(environment.apiUrl+'v1/herosliders/'+id, data, { headers: headers })
  }

But on the laravel server i get 422 (Unprocessable Content)
message => [‘The image field must be a file of type: png, jpg, jpeg.’]

so I debuged and I see when I code

$request->file('image')

i got null, but when I watch inside the PHP var $_FILES i got the image blob. So always gonna get that requires an image, but never is in laravel, I dont know what happened or what to do.

(I also tried adding or removing "Content-Type" in Headers, converting to blob but nothing)

2

Answers


  1. Chosen as BEST ANSWER

    About this error, I debugged today, and I got 2 errors.

    1. My angular and Laravel cache.
    2. The code $request->file('image') doesn't work on response()->json() so, always return null when I was testing.

    Also before this i checked if my Apache config was file_uploads=On and it was.


  2. You might need to add acceptance to your headers to receive the file as required format:
    if pdf => ‘Accept’, ‘application/pdf’
    if image => ‘Accept’, ‘image/jpg’

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search