我试图在使用Multer上传文件之前验证我收到的idProject是否为ObjectId或它是否存在于我的数据库中。但是它将保存文件,然后进行验证。
我已经尝试放入app.post('/ file',()=>)之类的索引,它可以工作,但我想将其保留在.controller.js和.route.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'));
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'
});
});
};
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);
};
答案 0 :(得分:0)
使用multer,您无法真正控制动态上传。 但是,您可以将其上传到temp文件夹中,然后检查ID是否存在。如果数据库中存在该文件,则可以将该文件移到另一个文件夹,否则,请删除该文件