3

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 ?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Jordan Enev. But your solution is not working. Thanks.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.