【问题标题】:How can i if dont send image implement default image on my user?如果不发送图像,我怎么能在我的用户上实现默认图像?
【发布时间】:2021-02-02 03:23:21
【问题描述】:

每个人 我的用户都有头像,但不是必需的,我不想要。所以我需要如果用户在注册或更新时向我发送图像,我会拍下这张照片并保存,这样我就可以了。如果用户不向我发送图片,我的问题是我无法提供默认图片

这是我的控制器代码:

//User Register Controller
const register = async (req, res, next) => {
    try {
        const {
            name,
            surname,
            username,
            phoneNumber,
            email,
            password,
            gender,
            profilPicture,
            birtDate,
        } = req.body;
        bcrypt.hash(password, 8, async (err, hash) => {
            try {
                const user = new User({
                    name,
                    surname,
                    username,
                    phoneNumber,
                    email,
                    password: hash,
                    gender,
                    profilPicture: 'http://localhost:4000/' + req.file.path || 'http://localhost:4000/public/images/profilePictures/defaultProfilePicture.png',
                    birtDate,
                });
                const createdUser = await user.save();
                const token = await createToken(createdUser);
                res.status(200).json({ token });
            } catch (err) {
                res.json(err);
            }
        });
    } catch (error) {
        res.json({ message: error.message });
    }
};

这是我的中间件 multer:

const multer = require('multer');
const stor = multer.diskStorage({
    destination:function(req,file,cb) {
        cb(null,'./public/images/profilePictures')
    },
    filename:function(req,file,cb){
        cb(null,'profilePicture-'+new Date().toISOString().replace(/:/g, '-')+file.originalname);
    }
})
const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, true);
    } else {
        cb(null, false);
    }
};
const upload = multer({
    storage: stor,
    limits: {
        fileSize: 1024 * 1024 * 5,
    },
    fileFilter: fileFilter,
});

module.exports = upload;
 

我的路线:

router.post('/register', upload.single('profilPicture'), userController.register);

【问题讨论】:

    标签: node.js mongodb express multipartform-data multer


    【解决方案1】:

    一种方法是在模型中设置默认值

    const mongoose = require("mongoose")
    
    const UserSchema = new mongoose.Schema({
        profilePicture: {
            type: String,
            default: 'defaultProfilePicture.png'
        }
    })
    
    module.exports = mongoose.model("Users", UserSchema)
    

    这样,如果用户没有上传个人资料图片,它将被设置为 defaultProfilePicture.png

    你不需要

    profilPicture: 'http://localhost:4000/' + req.file.path || 'http://localhost:4000/public/images/profilePictures/defaultProfilePicture.png',
    

    只是

    profilPicture: 'req.file.path'
    

    保存完整的 URL 绝不是一个好主意,因为您将来可能会选择更改它,例如远程文件存储或托管您的项目,然后 URL 将不再是 http://localhost:4000/。您最好保存图像的唯一名称和扩展名。

    【讨论】:

    • 我不需要默认图片,对不起,我不能告诉我自己,如果我可以发送没有图片的请求,抛出关于 req.bile.path is undefined 的错误
    • profilePicture: (req.file) ? req.file.path : 'public/images/profilePictures/defaultProfilePicture.png' 如果您打算在未来托管您的项目,保存 localhost 会导致问题。
    【解决方案2】:

    就这样试试吧:

    profilPicture: (req.file) ? 'http://localhost:4000/' + req.file.path : 'http://localhost:4000/public/images/profilePictures/defaultProfilePicture.png';
    

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 2012-01-31
      • 1970-01-01
      • 2012-07-23
      • 2022-01-08
      • 2014-10-12
      • 2020-01-19
      • 1970-01-01
      • 2013-12-08
      相关资源
      最近更新 更多