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

and


Where is the issue ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With