我有一個問題,express.js當multer我嘗試上傳 2 個有效影像和 1 個示例 pdf 以驗證所有影像時,它會將這兩個影像上傳到一個檔案夾中,然后它會拋出 pdf 格式無效的錯誤,可以我以某種方式首先驗證所有影像,然后上傳到檔案夾或拋出錯誤是有問題的這是我的代碼
const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './images');
},
filename: (req, file, cb) => {
cb(null, Date.now() '--' file.originalname);
}
});
const fileFilter = (req, file, cb) => {
// Reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
req.fileValidationError = 'File type not supported';
cb(null, false);
}
};
const upload = multer({
storage: fileStorageEngine,
limits: {
fileSize: 1024 * 1024 * 5 // Accept files to 5mb only
},
fileFilter: fileFilter
});
app.post('/multiple', upload.array('images', 3), async(req, res, next) => {
try {
console.log("POST Multiple Files: ", req.files);
if (await req.fileValidationError) {
throw new Error(req.fileValidationError);
} else {
for (let i = 0; i < req.files.length; i ) {
let storeImage = await StoreImages.create({
images: req.files[i].path
});
if (!storeImage) {
throw new Error('Sorry, something went wrong while trying to upload the image!');
}
}
res.status = 200;
res.render("index", {
success: true,
message: "Your images successfully stored!"
});
}
} catch(err) {
console.log("POST Multiple Error: ", err);
res.status = 406;
return res.render('index', {
error: true,
message: err.message
})
}
});
我想在插入檔案夾、服務器等之前驗證所有上傳的檔案...
uj5u.com熱心網友回復:
我通過在 fileFilter 函式中的 cb 函式中拋出錯誤找到了解決方案
const fileFilter = (req, file, cb) => {
// Reject a file
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png'){
cb(null, true);
}else{
cb(new Error('File type not supported'));
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/448866.html
標籤:javascript 节点.js 表示 穆尔特
