Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload using .fetch() in ReactJS

I am trying to upload file using .fetch() in ReactJS as Front End and Laravel as Back End. My ReactJS code is like below

update= (event) => {
let uploadImage =  event.target.file;
let form = new FormData()
form.append('uploadImage',uploadImage)

fetch('http://127.0.0.1:8000/api/addresses/upload', {
  headers: {
    'Authorization': 'Bearer ' + Auth.getToken(),
    'Content-Type': 'multipart/form-data',
  },
  method: "POST",
  body: form,
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}

My Laravel code is like below

public function fileUpload(StoreImageRequest $request)
    {
        $image           = $request->uploadImage;
        $imagename       = time() . $image->getClientOriginalName();
        $destinationPath = public_path('/images');
        $uploadValue     = $image->move($destinationPath, $imagename);
        if ($uploadValue) {
            return response()->json($imagename);
        }
    }

I am getting error like below

enter image description here

and

enter image description here

enter image description here

Where is the issue ?

like image 777
abu abu Avatar asked Sep 03 '26 08:09

abu abu


1 Answers

It's because you upload the image with form field name avatar, but in your Laravel method you access it with uploadImage.

So you can try change it to the following:

$request->avatar

Please checkout the Laravel Files documentation and make sure you follow their best practices.

like image 69
Jordan Enev Avatar answered Sep 06 '26 16:09

Jordan Enev



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!