mongoose 上传前在Multer中搜索

1aaf6o9v  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(140)

我试图验证,如果我收到的idProject是一个ObjectId或如果它存在于我的数据库上传文件之前与Multer。但它保存文件,然后验证。
我试过像app.post('/file',()=>)一样放入索引,它可以工作,但我想把它保存在. 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'));

字符串

  • project.controller.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'
            });
        });
};

  • file.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);
};

wa7juj8i

wa7juj8i1#

使用multer,你不能真正控制动态上传。但是,你可以做的是将它上传到一个临时文件夹中,然后检查id是否存在。如果它存在于你的数据库中,你可以将文件移动到另一个文件夹中,否则,删除该文件

kmb7vmvb

kmb7vmvb2#

除了@Kepotx answer之外,您还可以使用拦截器之类的东西来检查图像验证条件。如果验证不通过,您只需从本地/云上传中取消链接/删除文件。

if (condition) {
        for (const image of images) {
            const productFolderPath = path.join('products');
            const productFileName = path.basename(image.filename);
            const filePath = path.join(productFolderPath, avatarFileName);
            fs.unlink(filePath, (err) => {
                if (err) {
                    console.error('Error deleting file:', err);
                    throw new HttpException('Failed to delete avatar', HttpStatus.INTERNAL_SERVER_ERROR);
                } else {
                    console.log('File deleted successfully');
                }
            });
        }

        throw new HttpException(
            `Maximum image upload limit exceeded, please remove ${numberOfImagesToRemove} images`,
            HttpStatus.PAYLOAD_TOO_LARGE
        );
    }

字符串

相关问题