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

时间:2018-12-02 09:31:34

标签: node.js express multer

我正在尝试在express.js和MongoDB中创建用户个人资料。我正在使用multer上传图片。 Multer中间件始终在验证我的用户数据之前上传映像。如果用户验证失败,则将上传图像。但是,我想在验证用户数据后上传图像。这意味着,我将在控制器中检查用户数据,如果有效,则将上载图像并将用户数据存储到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`
    });
};

1 个答案:

答案 0 :(得分:2)

您可以使用两个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);