如果在表单提交中未选择默认图像,如何设置默认图像

时间:2019-11-07 20:33:06

标签: node.js express mongoose cloudinary

我有一个使用node.js,express和mongoose构建的CRUD应用程序。在这个应用程序中,我有一个表单,其中1个输入是用于上传图像的文件输入。我正在使用cloudinary,cloudinary存储和multer处理这些图像。如果用户上传图像,则可以将其成功添加到我的数据库中,并在以后进行渲染。我无法弄清楚的是,如果在文件输入中未选择默认图像,如何设置默认图像。这是我提交的表单:

findViewById(R.id.birthday).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
             if(hasFocus){
                new DatePickerDialog(EditActivity.this, date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
         }
   });

这是我的cloudinary配置:

router.post('/add', parser.single("image"), (req, res) => {
    const newContent = {
        name: req.body.contentName,
        userId: req.user.id,
        username: req.user.username,
        image: {
            url: req.file.url,
            id: req.file.public_id
        },
    }
    new Content(newContent)
    .save()
    .then(() => {
        req.flash('success_msg', 'Content added');
        res.redirect('/content')
    })
});

我浏览了cloudinary文档,发现有几个要添加的“ default_image”参数实例,但是无论我在cloudinary配置中的何处添加,我都会收到错误消息“无法读取未定义的属性'url'。可以在我的帖子中,在我的配置中或同时在两者中处理?作为参考,我的Content模型的image属性设置如下:

cloudinary.config({
    cloud_name: ******,
    api_key: ******,
    api_secret: ******
    });
    const storage = cloudinaryStorage({
    cloudinary: cloudinary,
    folder: "demo",
    allowedFormats: ["jpg", "png"],
    transformation: [{ width: 348, height: 236.81, crop: "limit" }]
    });
    const parser = multer({ storage: storage });

任何帮助表示感谢,谢谢!

1 个答案:

答案 0 :(得分:0)

访问图像时,您可以尝试:

cloudinary.url("sample.jpg", {width: 300, height: 100, crop: "scale",default_image: "avatar.png"});