this is how i upload videos
router.post('/vid', upload.array('files', 5), async (req, res) => {
try {
const video = new Video();
video.url = [];
req.files.forEach((file) => {
video.url.push(file.location);
});
const savedVideo = await video.save();
res.json({
message: 'Video uploaded successfully',
video: savedVideo
});
} catch (error) {
}
});
this how i upload pictures
router.post(`/products`, upload.array("photos", 10), async (req, res) => {
try {
let product = new Product();
product.photos.push(...req.files.map(({
location
}) => location));
await product.save();
} catch (error) {
}
});
this is my middleware
const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");
aws.config.update({
secretAccessKey: process.env.AWSSecretKey,
accessKeyId: process.env.AWSAccessKeyId,
region: 'eu-north-1', // Update the region to 'eu-north-1'
correctClockSkew: true
});
const s3 = new aws.S3();
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'ajibs',
acl: 'public-read',
metadata: (req, file, cb) => {
cb(null, { fieldName: file.fieldname });
},
key: (req, file, cb) => {
cb(null, Date.now().toString())
}
})
})
module.exports = upload;
both video and picture upload works fine if i use it in seperate route please how can i upload both pictures and videos in one route
if i do this
upload.array(["photos","files"], 10)
i get this error
MulterError: Unexpected field
please how can i go about this
this a working example ,what you'll need to do is change array to fields to get both photos and video, dont forget to add the photos name in your schema
router.post('/media', upload.fields([{ name: 'videos', maxCount: 5 }, { name: 'photos', maxCount: 10 }]), async (req, res) => {
try {
const video = new Video();
video.title = req.body.title;
video.url = [];
video.photos = [];
// Process uploaded videos
if (req.files['videos']) {
req.files['videos'].forEach((file) => {
video.url.push(file.location);
});
}
// Process uploaded photos
if (req.files['photos']) {
req.files['photos'].forEach((file) => {
video.photos.push(file.location);
});
}
console.log(video);
// Save the video to the database
const savedVideo = await video.save();
res.json({
message: 'Media uploaded successfully',
video: savedVideo
});
} catch (error) {
console.error(error);
res.status(500).json({
error: 'An error occurred while uploading the media'
});
}
});