【问题标题】:How can I set a default image if none is chosen in a form submit如果在表单提交中未选择任何图像,我该如何设置默认图像
【发布时间】:2020-03-04 11:50:55
【问题描述】:

我有一个使用 node.js、express 和 mongoose 构建的 CRUD 应用程序。在这个应用程序中,我有一个表单,其中一个输入是用于上传图像的文件输入。我正在使用 cloudinary、cloudinary 存储和 multer 来处理这些图像。如果用户上传了一张图片,我可以成功地将它添加到我的数据库中,然后稍后再渲染它。如果在文件输入中未选择任何内容,我无法弄清楚如何设置默认图像。这是我提交时的表单帖子:

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

我查看了 cloudinary 文档并找到了一些要添加的“default_image”参数实例,但无论我在 cloudinary 配置中的哪个位置添加它,我都会收到错误“无法读取未定义的属性 'url'。应该这样是在我的帖子中、在我的配置中还是在两者中处理?作为参考,我的 Content 模型的 image 属性设置如下:

        image: {
            url: {
                type: String,
                required: false
            },
            id: {
                type: String,
                required: false
            }
        },

任何帮助表示赞赏,谢谢!

【问题讨论】:

    标签: node.js express mongoose cloudinary


    【解决方案1】:

    访问图片时可以尝试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      相关资源
      最近更新 更多