【问题标题】:How to upload two images (not array) with different names on Cloudinary?如何在 Cloudinary 上上传两个名称不同的图像(不是数组)?
【发布时间】:2021-02-03 16:59:47
【问题描述】:

我正在使用 NodeJsMongoose 进行项目。我有一个具有两个不同图像属性的客户模式 (1) customer_profile_image (2) customer_logo 以及其他客户的详细信息。我想在添加新客户 (不是图像数组) 的同时使用 POST API 上传这两个图像,并且我希望在将每个图像上传到 Cloudinary 后将一个链接存储在数据库中。我之前使用 Cloudinary 来上传一张图片或一组图片,因为上传同名图片很容易,但在这种情况下,我不知道如何上传两张不同名称的图片。我该怎么办? Cloudinary 的上传功能是否需要多个参数?如果是,如何确定服务器上当前正在上传哪个图像以及哪个链接用于哪个图像? 下面是我在 Cloudinary 上上传单张图片的功能:

    app.post('/customer', upload.single('customer_profile_image'), async (request, response, next) => {
const path = request.file.path;
var uniqueFilename = new Date().toISOString();
var img = await cloudinary.uploader.upload(
            path, {
            public_id: `blog/${uniqueFilename}`,
            tags: `blog`
        }, // directory and tags are optional
            async function (err, image) {
                if (err) return (err)
                fs.unlinkSync(path);
                // console.log(image);
                var customer = new Customer(request.body);
                customer.customer_profile_image= await image.secure_url
})
})

【问题讨论】:

    标签: node.js mongoose cloudinary


    【解决方案1】:

    您需要在自己的上传调用中单独上传每张图片,并为该图片指定公共 ID。 Cloudinary 不支持在一次上传调用中上传多张图片。此外,如果您将上传调用更改为使用文件夹参数而不是公共 ID,它将在末尾附加一个随机字符串。例如,Cloudinary 的上传都可以是这样的:

    var customer = new Customer(request.body);
    const path = request.file.path;
    var customer_profile_image = await cloudinary.uploader.upload(
                path, {
                folder: `blog/customer_profile_image`,
                // public id = blog/customer_profile_image/<randomly-generated-string>
                // e.g. blog/customer_profile_image/djqhfhwidhalwdi
                tags: `blog`
            }, // directory and tags are optional
                async function (err, image) {
                    if (err) return (err)
                    customer.customer_profile_image = image.secure_url
    })
    

    同样,您需要为 customer_logo 进行单独的上传调用

    var customer_logo = await cloudinary.uploader.upload(
                path, {
                folder: `blog/customer_logo`,
                // public id = blog/customer_logo/<randomly-generated-string>
                // e.g. blog/customer_logo/sdjoqnfhjahslq
                tags: `blog`
            }, // directory and tags are optional
                async function (err, image) {
                    if (err) return (err)
                    customer.customer_logo = image.secure_url
    })
    

    【讨论】:

    • 通过单独的上传调用,您是指单独的 post api 吗?您想说的是我必须制作两个 api,其中一个将 customer_profile 作为 upload.single 函数中的参数,另一个将客户徽标作为参数。例如 upload.single('customer_profile') & upload.single('customerLogo') ??
    • 如何在一个帖子调用中实现多张图片上传??
    • 我包含的两个示例应该在您的 app.post 中,只要您在该 post 调用中传递两个图像。
    猜你喜欢
    • 2018-10-10
    • 2019-08-08
    • 2021-10-21
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2021-08-29
    • 2017-09-15
    相关资源
    最近更新 更多