要安装multer-gridfs-storage包,可以按照以下步骤进行操作:
npm install multer-gridfs-storage
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const storage = new GridFsStorage({
url: 'mongodb://localhost:27017/mydatabase', // 替换为你的MongoDB连接字符串
options: { useNewUrlParser: true, useUnifiedTopology: true },
file: (req, file) => {
const match = ["image/png", "image/jpeg"];
if (match.indexOf(file.mimetype) === -1) {
const filename = `${Date.now()}-some-file-name.${file.originalname.split('.')[file.originalname.split('.').length - 1]}`;
return filename;
}
return {
bucketName: "photos",
filename: `${Date.now()}-some-file-name.${file.originalname.split('.')[file.originalname.split('.').length - 1]}`
};
}
});
const upload = multer({ storage });
app.post('/upload', upload.single('file'), (req, res) => {
// 处理文件上传请求的逻辑
});
以上代码示例假设你已经安装了multer和mongodb模块,并且有一个名为"photos"的GridFS存储桶供你存储文件。请根据你的实际需求进行相应的更改。