node.js - 如何将多个文件上传到mongodb
问题描述
我正在尝试使用gridfs
and将多个文件上传到 mongo db multer
。
我知道要上传单个文件,您必须调用此函数
const conn = mongoose.connection;
const mongoURI = "mongodb://localhost:27017/moto_website";
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploaded_images'); //collection name
});
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploaded_images' //collection name
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
router.post('/posts', upload.single('file'), (req, res) => {...})
所以当upload.single(<file_name>)
被称为文件上传时,但我怎样才能上传多个文件?
在multer-gridfs-storage
npm 包页面中有这个例子
const sUpload = upload.single('avatar');
app.post('/profile', sUpload, (req, res, next) => {
/*....*/
})
const arrUpload = upload.array('photos', 12);
app.post('/photos/upload', arrUpload, (req, res, next) => {
/*....*/
})
const fUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', fUpload, (req, res, next) => {
/*....*/
})
我应该使用哪一个以及我应该通过哪些参数?
解决方案
我找到了我正在寻找的东西,
// use this one for upload a single file
const sUpload = upload.single('avatar'); // avatar is the name of the input[type="file"] that contains the file
app.post('/profile', sUpload, (req, res, next) => {
/*....*/
})
// use this one for upload an array of files
// You have an array of files when the input[type="file"] has the atribute 'multiple'
const arrUpload = upload.array('photos', 12); // photos is the name of the input[type="file"] that contains the file
app.post('/photos/upload', arrUpload, (req, res, next) => {
/*....*/
})
// use this one for upload multipe input tags
// {name: <name of the input>, maxCount: <the number of files that the input has>}
const fUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', fUpload, (req, res, next) => {
/*....*/
})
推荐阅读
- javascript - 如何使用 JavaScript fetch 将文件数据发布到 Gitlab 项目
- java - Selenium Webdriver 问题无法打开谷歌浏览器
- python - Matplotlib - 对齐网格
- python - 如何使用 django 过滤器或以某种方式获取“最近”元素
- java - 来自 Firebase 的数据未显示在 RecyclerView 中
- php - 如果表单验证失败,则使用自定义请求类(laravel 5.8)通过输入重定向回来
- python - Flask 会话数据可以被用户(威胁参与者)更改吗?
- android - Android Studio 中的 Gradle 依赖项
- three.js - 我可以将 THREE.js 材料放在 gltf 模型上吗?
- git - 如何在 Mac 上为 Fork 配置 SSH 私钥?