使用 Multer 和 Node 将多个文件上传到 mongoDB
Multiple files upload to mongoDB using Multer and Node
如何使用 Node 和 multer 将多个文件上传到 mongoDB。这是我尝试(当然不成功)来处理它。 uploadImg.array() 似乎运行良好,因为它在本地创建文件。问题是我无法在 mongoDB
中创建新的上传
router.post("/img", auth, uploadImg.array("path", 12), async (req, res) => {
try {
Promise.all(
req.files.map(async (file) => {
const newUpload = new Uploads({
_id: new Types.ObjectId(),
path: file.path,
owner: req.user.userId,
});
return await newUpload.save();
})
);
res.status(201).json(newUpload);
} catch (e) {
res
.status(500)
.json({ message: "Something went wrong in /uploads/img", error: e });
}
});
req.files 看起来像这样:
[
{
fieldname: 'path',
originalname: 'cover.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '1608637632307cover.jpg',
path: 'uploads\1608637632307cover.jpg',
size: 77716
},
{
fieldname: 'path',
originalname: 'mainImg.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '1608637632310mainImg.jpg',
path: 'uploads\1608637632310mainImg.jpg',
size: 111086
}
]
有什么想法吗? :)
此解决方案非常有效,您只需处理 res.status:
router.post("/img", auth, uploadImg.array("path", 12), async (req, res) => {
Promise.all(
req.files.map(async (file) => {
const newUpload = new Uploads({
_id: new Types.ObjectId(),
path: file.path,
owner: req.user.userId,
});
return await newUpload.save();
})
)
.then(res.status(201).json("files successfully uploaded"))
.catch((e) => {
res
.status(500)
.json({ message: "Something went wrong in /uploads/img", error: e });
});
});
如何使用 Node 和 multer 将多个文件上传到 mongoDB。这是我尝试(当然不成功)来处理它。 uploadImg.array() 似乎运行良好,因为它在本地创建文件。问题是我无法在 mongoDB
中创建新的上传router.post("/img", auth, uploadImg.array("path", 12), async (req, res) => {
try {
Promise.all(
req.files.map(async (file) => {
const newUpload = new Uploads({
_id: new Types.ObjectId(),
path: file.path,
owner: req.user.userId,
});
return await newUpload.save();
})
);
res.status(201).json(newUpload);
} catch (e) {
res
.status(500)
.json({ message: "Something went wrong in /uploads/img", error: e });
}
});
req.files 看起来像这样:
[
{
fieldname: 'path',
originalname: 'cover.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '1608637632307cover.jpg',
path: 'uploads\1608637632307cover.jpg',
size: 77716
},
{
fieldname: 'path',
originalname: 'mainImg.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '1608637632310mainImg.jpg',
path: 'uploads\1608637632310mainImg.jpg',
size: 111086
}
]
有什么想法吗? :)
此解决方案非常有效,您只需处理 res.status:
router.post("/img", auth, uploadImg.array("path", 12), async (req, res) => {
Promise.all(
req.files.map(async (file) => {
const newUpload = new Uploads({
_id: new Types.ObjectId(),
path: file.path,
owner: req.user.userId,
});
return await newUpload.save();
})
)
.then(res.status(201).json("files successfully uploaded"))
.catch((e) => {
res
.status(500)
.json({ message: "Something went wrong in /uploads/img", error: e });
});
});