mongoose 当我尝试使用multer在node.js中上传多个文件时遇到问题

cpjpxq1n  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(156)

我不能在DB中添加多个文件,但当我添加单个文件时,它工作。问题还在于,当我添加多个文件时,文件保存在目标中,但不在DB中。
我的问题是,当我保存单个文件时,它被保存在数据库中,但当我尝试保存多个文件时,图像被保存在文件中,而不是保存在我在数据库中创建的(image)属性中。简而言之,我的问题是,如果我想上载多个图像,它看起来像是我上载了它们,但它没有保存到数据库中。

zsbz8rwp

zsbz8rwp1#

Multer中有两个函数:
对于要上载单个文件,请用途:

upload.single('avatar')

对于要上载多个文件,请用途:

upload.array('photos', 12) //here 12 is max number of files to upload.

请参考以下示例代码:

const express = require("express");
const multer = require("multer");
const app = express();
const multerStorage = multer.memoryStorage();
// Filter files with multer if you need
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("upload only images.", false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter,
});
app.post('/singleUpload', upload.single('avatar'), function (req, res,
next) {
// req.body will hold the text fields, if there were any
console.log(req.file);//req.file is the `avatar` file. here avatar is
input field name
})
app.post('/multipleUpload', upload.array('photos', 12), function (req,
res, next) {
// req.body will contain the text fields, if there were any
// req.files is array of `photos` files.here avatar is
input field name
console.log(req.files);
})

希望这对你有帮助。

相关问题