abu abu
abu abu

Reputation: 7028

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 ?

Upvotes: 3

Views: 3756

Answers (2)

Batur
Batur

Reputation: 549

I had the same issue. I fixed it by removing the content type.

Please check this article

https://upmostly.com/tutorials/upload-a-file-from-a-react-component

Upvotes: 0

Jordan Enev
Jordan Enev

Reputation: 18644

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.

Upvotes: 1

Related Questions