MongoDB中未保存Cloudinary图像路径

问题描述 投票:0回答:1

我正在构建一个快速应用程序,其中包含一个表单,可以选择上传单个图像。我使用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路径。请有人帮我解决这个问题。谢谢。

node.js mongodb image express cloudinary
1个回答
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);

If you are using Cloudinary's uploader, according to Cloudinary website:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.