node.js - 上传前在 Multer 中验证
问题描述
我试图验证我收到的 idProject 是 ObjectId 还是在使用 Multer 上传文件之前它是否存在于我的数据库中。但它会保存文件然后验证。
我试过把 app.post('/file', ()=>) 这样的索引放进去,它可以工作,但我想把它保存在 .controller.js 和 .route.js 中
- index.js
const storage = multer.diskStorage({
destination: path.resolve('./uploads'),
filename: (req, file, cb, filename) => {
cb(null, uuid() + path.extname(file.originalname));
}
});
app.use(multer({storage: storage}).single('file'));
- 项目控制器.js
projectCtrl.addFileToProject = async (req, res) => {
const { id } = req.params;
await Project.findById(id)
.then((project) => {
if(project === null){
res.json({
status: 'Fail to Add File 1'
});
}
else{
fileCtrl.uploadFile(req, async (cb) => {
await Project.findByIdAndUpdate(id, {$addToSet: {files: cb}})
});
res.json({
status: 'File Added to Project'
});
}
})
.catch(() => {
res.json({
status: 'Fail to Add File 2'
});
});
};
- 文件.controller.js
fileCtrl.uploadFile = async (data, cb) => { var now = moment(); const { size } = data.file; const { mimetype } = data.file; var icon; if (mimetype === mime.lookup('.pdf')) { icon = 'pdfIcon'; } else if (mimetype === mime.lookup('.doc')) { icon = 'docIcon'; } else if (mimetype === mime.lookup('.docx')) { icon = 'docIcon'; } else if (mimetype === mime.lookup('.xls')) { icon = 'xlsIcon'; } else if (mimetype === mime.lookup('.xlsx')) { icon = 'xlsIcon'; } else if (mimetype === mime.lookup('.ppt')) { icon = 'pptIcon'; } else if (mimetype === mime.lookup('.pptx')) { icon = 'pptIcon'; } else if (mimetype === mime.lookup('.jpg')) { icon = 'jpgIcon'; } else if (mimetype === mime.lookup('.png')) { icon = 'pngIcon'; } else if (mimetype === mime.lookup('.txt')) { icon = 'txtIcon'; } else if (mimetype === mime.lookup('.zip')) { icon = 'zipIcon'; } else { icon = 'fileIcon'; } var decimals=2; if(size == 0) return '0 Bytes'; var k = 1024, dm = decimals <= 0 ? 0 : decimals || 2, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], i = Math.floor(Math.log(size) / Math.log(k)); var fileSize = parseFloat((size / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; const file = new File(); file.filename = data.file.filename; file.author = data.body.author; file.path = '/uploads/' + data.file.filename; file.originalname = data.file.originalname; file.icon = icon; file.size = fileSize; file.created_at = now; await file.save(); cb(file._id); };
解决方案
使用 multer,您无法真正动态控制上传。但是,您可以将其上传到临时文件夹中,然后检查 id 是否存在。如果它存在于您的数据库中,您可以将该文件移动到另一个文件夹中,否则,删除该文件
推荐阅读
- nlp - 使用 NLP 匹配标签
- node.js - 首次登录失败,刷新页面强制用户在Angular+(Node/express).js中注销
- ios - 如何从字符串转换或类型转换为 binaryInteger?
- javascript - 为什么它没有在输出中显示范围值?
- flutter - 如何在颤动中展开和折叠容器
- erlang - maps:from_list 是否保证保留相反的顺序?
- php - Laravel 中的缓存
- python - python - 如何在python列表中的每5个字符串后添加换行符?
- python - Python EmailMessage().addAttachment; 如何附加 ZIP 文件?
- mockup-tool - “富文本”和“HTML 文本”有什么区别?