[英]how to validate a minimum number of files uploaded with multer?
我想用 multer 上傳文件,但我需要如果同時加載的文件少於 3 個,它會顯示錯誤並且不會將它們保存在我的服務器上。 我知道如何限制最大文件數,但我不知道如何限制最小文件數。 這是我的 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;
您可以在路由中添加中間件或驗證。
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'})
}
})
使用中間件數組:
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.