'I.m Getting "Call to a member function getClientOriginalName() on null" when uploading image with axios in laravel blade
Why I'm getting
Call to a member function getClientOriginalName() on null
when uploading an image as below. Request payload is looks like
------WebKitFormBoundaryU2XJIVhmCHdi06EH
Content-Disposition: form-data; name="image"; filename="download (3).jfif" Content-Type: image/jpeg
------WebKitFormBoundaryU2XJIVhmCHdi06EH--
in my blade file
<form action="" id="img_form" method="POST" enctype="multipart/form-data" onchange="uploadImage()">
@csrf
<input type="file" id="image" name="image" onchange="uploadImage()">
</form>
Js Code
function uploadImage(event) {
console.log('image');
const formData = new FormData();
const imagefile = document.querySelector('#image');
formData.append("image", imagefile.files[0])
// formData.append("image_2", imagefile.files[0]);
console.log('formdata' +formData);
axios.post('upload/image', formData, {
headers: {
'Content-Type': imagefile.type
// 'Content-Type': 'multipart/form-data;charset=utf-8;boundary=' + Math.random().toString().substr(2)
}
}).then(response => {
console.log('response' + response.data);
});
}
In My laravel Controller
public function uploadImage(Request $request){
$file = $request->file('image');
$name = $file->getClientOriginalName().'-'.time() ;
$filePath = 'images/' . $name;
Storage::disk('public')->put($filePath, file_get_contents($file));
$get_url = Storage::disk('public')->url($filePath);
return response()->json([
'name' => $name,
'url' => $get_url
]);
}
Solution 1:[1]
your request dosent have file as 'image_ad' , so use it:
$file = $request->file('image');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | amirhosein hadi |