I keep getting req.file is undefined from the api when trying to upload an image from the frontend. I use Laravel's guzzle-http to post the data. When I use postman's form-data ,however, the image gets uploaded successfully so I think it might have to do with something on the frontend.
If you can point me to the right direction that could help a lot.
Heres what I have so far
Node js Controller
exports.post_image = (req, res, next) => {
console.log(req.file);// outputs undefined
//validate file is present
if (!req.file) return res.status(400).json({message: 'Please upload a image!'});}
Node js Route
router.post('/', upload.single('image'), ImageController.post_image);
Laravel Controller
public function store(Request $request)
{
$validatedData = Validator::make($request->all(), [
'image' => 'required|image:jpeg,png,jpg|max:2048',
])->validate();
if ($request->hasFile('image')) {
$image = $validatedData['image'];
}
//dd($image);// returns the file and its properties
$url = 'http://localhost:3000/upload';
$response = Http::post($url, [
'image' => $image
]);
dd(json_decode($response));// response is 'Please upload a image!'
$response_decode = json_decode($response);
$message = $response_decode->message;
session()->flash('success', $message);
return redirect()->action('ImageController@index');
}
Html Page
<form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="form-group">
<label for="image">Image</label>
<input type="file" id="image" name="image" accept="image/png,image/jpeg" class="form-control">
</div>
<div class="form-group">
<button class="btn btn-success">Upload</button>
</div>
</form>