MongoDB中未保存Cloudinary图像路径

时间:2018-03-03 23:46:37

标签: node.js mongodb image express cloudinary

我正在构建一个快速应用程序,其中包含一个表单,其中包含上传单个图像的选项。我使用cloudinary sdk为node.js nad返回成功实现了图像上传。我可以在我的控制台中看到图像网址并对其进行测试以确定。像:

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中保存此路径时,会出现此问题。我有这个片段来保存表格中的输入和图像,如下所示:

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指南针中,我已经检查过,但图像的值是一个空字符串,如:' '。这是新创建的产品的片段:

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

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

1 个答案:

答案 0 :(得分:0)

如何将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 我希望它可以提供帮助。 :)