Recently, I followed the advice of several YouTubers and used multer for file upload in my project. However, despite correctly defining all the functions, req.file always appears as undefined.
booking_route.js
const express = require('express');
const router = express.Router();
const multer = require('multer');
// Storage
const storage = multer.diskStorage({
destination: function (request, file, callback) {
callback(null, './public/uploads/images')
},
filename: function (request, file, callback) {
callback(null, Date.now() + file.originalname)
}
})
// Upload Params
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 3
}
})
const { bookHallForEvent } =
require('../controllers/booking_controller')
router.post('/events', upload.single('image'), bookHallForEvent)
module.exports = router
booking_controller.js
const eventModel = require('../models/event_model')
const bookHallForEvent = async (req, res) => {
try {
console.log(req.file);
const { hallID, timeSlot, date, name, description, username } =
req.body;
const oldEvent = await eventModel.findOne({ hall_id: hallID, date:
date, time_slot: timeSlot })
if (oldEvent) {
res.status(400).json({
error: "Event already booked in the same date and timeslot
for this venue"
})
} else {
const event = await eventModel.create({
name,
description,
date,
time_slot: timeSlot,
hall_id: hallID,
user_id: username
})
res.status(201).json({
event_res: event
})
}
} catch (err) {
console.log(err);
}
}
module.exports = {
bookHallForEvent
}
IndividualHallView.vue
<form
@submit.prevent="handleBooking"
method="POST"
enctype="multipart/form-data"
>
<div class="modal-body">
<div class="mb-3">
<label for="BatsmanLabel" class="form-label">Event name</label>
<input
type="text"
class="form-control"
v-model="bookingData.event_name"
id="NameInput"
/>
</div>
<div class="mb-3">
<label for="BowlerLabel" class="form-label"
>Event Description</label
>
<textarea
class="form-control"
id="exampleFormControlTextarea1"
v-model="bookingData.event_desc"
rows="3"
></textarea>
</div>
<div class="mb-3">
... (Additional code snippets continue here) ...
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
>
Cancel
</button>
<button data-bs-dismiss="modal" class="btn btn-primary">
Submit
</button>
</div>
</form>
I hope this issue is just a minor bug causing the problem.
P.S. Apologies for the inconsistent code formatting.