gpt4 book ai didi

node.js - 在 express.js 中验证用户数据后如何上传图像

转载 作者:搜寻专家 更新时间:2023-10-31 23:50:21 25 4
gpt4 key购买 nike

我正在尝试在 express.js 和 MongoDB 中创建用户配置文件。我正在使用 multer 进行图片上传。 Multer 中间件总是在验证我的用户数据之前上传图像。如果用户验证失败,仍然会上传图像。但是,我想在验证用户数据后上传图片。这意味着,我将检查 Controller 中的用户数据,如果它是有效的,那么我将上传图像并将用户数据存储到 MongoDB。我怎样才能做到这一点?提前致谢!

multerConfig.js

   exports.multerConfig = (multer) => {
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads/');
},
filename: (req, file, cb) => {
cb(null, 'img-' + new Date().toISOString() + '-' + file.originalname);
}
});

const fileFilter = (req, file, cb) => {
(file.mimetype === 'image/png' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg')
? cb(null, true)
: cb(null, false)
};

return multer({
storage: storage,
limits: { fileSize: 1048576 },
fileFilter: fileFilter
});
};

user.js(路由)

const multer = require('multer');
const express = require('express');
const userController = require('../controllers/user');
const { multerConfig } = require('../utility/multerConfig');
const validateObjectId = require('../middleware/validateObjectId');
const asyncErrorHandler = require('../middleware/asyncErrorHandler');

const router = express.Router();
const upload = multerConfig(multer);

router.post('/', upload.single('image'), asyncErrorHandler(userController.createUser));

module.exports = router;

user.js( Controller )

 const { User, validate } = require('../models/user');

const { deleteFile } = require('../utility/fileUtility');
const { failed, success } = require('../utility/utility');


exports.createUser = async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send({ ...failed, message: error.details[0].message });

const { name, address, mobile, email, password } = req.body;

if (!req.file) return res.status(400).send({ ...failed, message: `you have to upload an image!` });

const isUserExist = await User.find().or([{ mobile }, { email }]);
if (isUserExist.length > 0) return res.status(409).send({ ...failed, message: `${name} is already exists!` });

const image = req.file.path;
const newUser = new User({ name, address, mobile, email, password, image });
const savedUser = await newUser.save();

if (!savedUser) return res.status(500).send({ ...failed, message: `user ${name} is failed to save!` });

res.send({
...success,
data: savedUser,
message: `user ${name} is saved successfully`
});
};

最佳答案

您可以使用两个 multer 中间件(一个用于解析文本,一个用于上传文件)。

假设您有一个带有name(文本字段)和avatar(文件字段)的表单,您可以这样做:

var express = require('express');
var multer = require('multer');

var app = express();
var upload = multer({ dest: 'uploads/' });

app.post('/profile',
upload.none(), function (req, res, next) {
// validate `req.body.name` here
// and call next(err) if it fails
next();
},
upload.single('avatar'), function (req, res, next) {
// file is now uploaded, save the location to the database
res.end('done!');
});

app.listen(9000);

关于node.js - 在 express.js 中验证用户数据后如何上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53579001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com