[英]how to validate a minimum number of files uploaded with multer?
I want to upload files with multer, but I need that if less than 3 files are loaded simultaneously it shows an error and does not save them on my server.我想用 multer 上传文件,但我需要如果同时加载的文件少于 3 个,它会显示错误并且不会将它们保存在我的服务器上。 I know how to limit a maximum number of files, but I don't know how to limit a minimum number of files.我知道如何限制最大文件数,但我不知道如何限制最小文件数。 This is my Multer configuration这是我的 Multer 配置
const multer = require('multer');
function uploadFile() {
const storage = multer.diskStorage({
destination: './public/files',
filename: function (_req, file, cb) {
var extension = file.originalname.slice(file.originalname.lastIndexOf('.'));
cb(null, Date.now() + extension);
}
});
const upload = multer({
storage,
limits: {fileSize: 11657128, files: 3},
fileFilter: function(req, file, cb) {
let type = req.files
type?cb(null, true):cb(new Error ('no es un archivo de tipo texto plano'));
}}
).array('file');
return upload;
}
module.exports = uploadFile;
You can add a middleware or a validation at your routes.您可以在路由中添加中间件或验证。
app.post('/your/route', upload.array('field', 3), function (req, res) {
if (req.files.length !== 3) {
return res.status(400).json({ error: 'Three files is required'})
}
})
With array of middleware:使用中间件数组:
function validUploadLength (req, res, next) {
if (req.files.length !== 3) {
return res.status(400).json({ error: 'Three files is required'})
}
next()
}
app.post('/your/route', [upload.array('field', 3), validUploadLength], function (req, res) {
/// Your code
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.