'Upload/Store multiple files with multer, i.e image and pdf with single request in nodejs
The following code works to upload a single image to upload an image and store its path in the database, now I can't find a way to upload an image and a pdf file in a single request and also store their paths in the database. I need to upload both of them when I create the user.
user-routes.js
const express = require("express");
const router = express.Router();
const { getUser, createUser } = require("./user-controller");
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads/");
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString().replace(/:/g, "-") + file.originalname);
},
});
const fileFilter = (req, file, cb) => {
if (
file.mimetype === "image/jpeg" ||
file.mimetype === "image/png" ||
file.mimetype === "image/jpg"
) {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 25,
},
fileFilter: fileFilter,
});
router.post("/", upload.single("userImage"), async (req, res) => {
const newUser = await User.create({ ...req.body, userImage: req.file.path });
console.log(req.file);
res.send("CREATE USER");
};);
user-model.js
const userSchema = new mongoose.Schema({
name: String,
job: String,
userImage: String,
userDoc: String,
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
