【问题标题】:Cloudinary Image Path NOT Saved in MongoDBCloudinary 图像路径未保存在 MongoDB 中
【发布时间】:2018-08-11 22:16:14
【问题描述】:

我正在构建一个快速应用程序,该应用程序具有一个可以选择上传单个图像的表单。我已经使用 cloudinary sdk for node.js nad 实现了图像上传,返回成功。我可以在我的控制台中看到图像 url 并对其进行测试以确保。喜欢:

Product Cloud Image URL:        http://res.cloudinary.com/joey17/image/upload/v1520120085/bte0bhzl6ljcuqmr3vgn.jpg
img url value:    http://res.cloudinary.com/joey17/image/upload/v1520120085/bte0bhzl6ljcuqmr3vgn.jpg

当我尝试在 mongodb 中保存此路径时出现问题。我有这个 sn-p 来保存表单中的输入和图像,如下所示:

let imgUrl = "";

    cloudinary.uploader.upload(req.files.image.path, (resultImage) => {
        console.log('Product Cloud Image URL:\t' + resultImage.url);
        imgUrl = resultImage.url;
        console.log('img url value:\t' + imgUrl);
    });

    Products.findOne({slug: slug})
        .select('_id title slug image desc price category')
        .exec()
        .then(product => {
            if (product) {
                req.flash('danger', 'Product Title Already Exists');
                res.render('admin/add_product', {
                    title: title,
                    slug: slug,
                    price: price,
                    desc: desc,
                    category: cat,
                    image: imgUrl
                });
            } else { // start reading from here... sorry had to include the other parts above
                console.log('Unique Product Slug');

                let price2 = parseFloat(price).toFixed(2);

                let product = new Products({
                    title: title,
                    slug: slug,
                    price: price2,
                    desc: desc,
                    category: cat,
                    image: imgUrl
                });

                product.save()
                    .then(data => {
                        console.log('Product Created:\t' + data);

                        req.flash('success', 'New Product Created');
                        res.redirect('/admin/products');
                    })
                    .catch(e => {
                        console.error('Error Saving Product:\t' + e);
                    });


            }
        })
        .catch(err => {
            console.error(err);
        });
}

});

在 mongo compass 中,我检查过,但图像的值是一个空字符串,例如:' '。这是新创建的产品的 sn-p:

 _id: ObjectId("5a9b307937766901104addf8")
 title: "Blue Shirt"
 slug: "blue-shirt"
 price: 123
 desc: "a blue ocean"
 category: "clothes"
 image: ""
 __v: 0

我不明白为什么不保存 cloudinary 路径。请有人帮我解决这个问题。谢谢。

【问题讨论】:

  • 我的错,我应该将产品保存在 cloudinary 回调中。第一个对此答案发表评论的人将被接受。提前致谢。

标签: node.js mongodb image express cloudinary


【解决方案1】:

你把你的Products.findOne() 放到cloudinary.uploader.upload() 的回调中怎么样。因为上传函数是同步调用。所以,你必须让你的保存功能等待它。

let imgUrl = "";

    cloudinary.uploader.upload(req.files.image.path, (resultImage) => {
        console.log('Product Cloud Image URL:\t' + resultImage.url);
        imgUrl = resultImage.url;
        console.log('img url value:\t' + imgUrl);
        
        Products.findOne({slug: slug})
        .select('_id title slug image desc price category')
        .exec()
        .then(product => {
            if (product) {
                req.flash('danger', 'Product Title Already Exists');
                res.render('admin/add_product', {
                    title: title,
                    slug: slug,
                    price: price,
                    desc: desc,
                    category: cat,
                    image: imgUrl
                });
            } else { // start reading from here... sorry had to include the other parts above
                console.log('Unique Product Slug');

                let price2 = parseFloat(price).toFixed(2);

                let product = new Products({
                    title: title,
                    slug: slug,
                    price: price2,
                    desc: desc,
                    category: cat,
                    image: imgUrl
                });

                product.save()
                    .then(data => {
                        console.log('Product Created:\t' + data);

                        req.flash('success', 'New Product Created');
                        res.redirect('/admin/products');
                    })
                    .catch(e => {
                        console.error('Error Saving Product:\t' + e);
                    });


            }
        })
        .catch(err => {
            console.error(err);
        });
}

});
    });

    

上传到特定文件夹:

首先,转到此链接https://cloudinary.com/console/settings/upload 并找到“上传预设”部分以创建预设,让您选择要使用的文件夹。其次,你的上传代码应该是这样的(我用的是axios)

const fd = new FormData();
fd.append('upload_preset', 'Your preset name');
fd.append('file', file);
return axios.post(API_CLOUDINARY_UPLOAD_URL, fd, { headers: { 'X-Requested-
With': 'XMLHttpRequest' } }).then(result => result.data);

如果您使用 Cloudinary 的上传器,根据 Cloudinary 网站:

cloudinary.v2.uploader.unsigned_upload("sample.jpg", "unsigned_1", 
{ cloud_name: "demo" }, 
function(error, result) {console.log(result) });

unsigned_1 是您的预设名称。 完整的文档在这里:Documentation 我希望它可以帮助。 :)

【讨论】:

  • 是的,我想通了。 SO没有实时重新加载。谢谢朋友
  • 图片可以在线保存到文件夹吗?
  • 是的,您可以前往 Cloudinary 设置部分设置上传预设,让您分配文件夹。代码上传图片时,可以选择使用不同的预设来控制要上传到哪个文件夹。
  • 我检查了文档和控制台,但不明白。你能分享一个例子吗?
  • 这个注释很难显示代码。所以,我会把它贴在我原来的答案中。
猜你喜欢
  • 2016-04-06
  • 1970-01-01
  • 2015-10-12
  • 2021-05-05
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 2020-01-25
相关资源
最近更新 更多