I can't figure out why I'm getting this server error Call to a member function getClientOriginalName() on null
when trying to upload a file (POST request) to my endpoint when trying on the browser.
It works fine on Postman, I'm able to upload successfully. Its just weird how I don't get the aforementioned error on Postman but I do get it when trying on the browser. I believe my JS is off but I'm not too sure as I've tried everything under the sun to try to rectify this but no avail, I've hit a wall.
How can I rectify this?
Note: For more detail, here's a discrepancy I'm facing: When I dd($request->all());
and submit the form on the browser - I get (which's incorrect):
array:1 [
"userUpload" => []
]
When I do it on Postman - I get (which's correct):
array:1 [
"userUpload" => Illuminate\Http\UploadedFile {#1325
-test: false
-originalName: "gallery12.jpg"
-mimeType: "image/jpeg"
-error: 0
#hashName: null
path: "/tmp"
filename: "php4FMimY"
basename: "php4FMimY"
pathname: "/tmp/php4FMimY"
extension: ""
realPath: "/tmp/php4FMimY"
aTime: 2022-01-20 19:42:45
mTime: 2022-01-20 19:42:45
cTime: 2022-01-20 19:42:45
inode: 3146782
size: 519395
perms: 0100600
owner: 1000
group: 1000
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
]
Here's my JS:
const fileUpload = () => {
const url = 'http://localhost:8005/api/file-upload';
let input = document.querySelector('input[type="file"]')
let data = new FormData()
data.append('file', input.files[0])
const postData = {
'userUpload' : input.files[0]
}
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
}
// All of these are displaying the correct data
console.log(authToken);
console.log(postData);
console.log(headers);
axios.post(url, postData, {headers})
.then(resp => {
console.log(resp);
}).catch(error => {
console.log(error);
});
}
return (
<form encType="multipart/form-data" method="POST">
<input type="file" name="userUpload" required/>
<Button variant="primary" onClick={fileUpload}>Upload!</Button>
</form>
);
Here's FileUploadController.php:
public function fileUpload(Request $request)
{
// dd($request->all());
$path = env('AWS_S3_PATH');
$file = $request->file('userUpload');
$imgName = $file->getClientOriginalName();
$bucket = env('AWS_BUCKET');
$region = env('AWS_REGION');
$url = "https://{$bucket}.s3.{$region}.amazonaws.com{$path}{$imgName}";
$userId = Auth::user()['UserID'];
$file->storeAs(
$path, // Folder
$imgName, // Name of image
's3' // Disk Name
);
$data = [
'url' => $url,
'UserID' => $userId,
'isUploaded' => true,
'timeStamp' => time(),
'updated_at' => time()
];
Upload::create($data);
return $data;
}