使用Node.js在一个请求中将多个图像上传到Cloudinary的最有效方法是什么?

mlnl4t2r  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(94)

我想一次上传多张图片,我使用cloudinary,目前我可以在cloudinary上上传多张图片,但我认为这不是一个好的方法,因为我每次都为每张图片提出单独的请求。我已经检查了社区上类似的答案,但这些都不起作用。

const vehicleIcon = await cloudinary.uploader.upload(
    req.files.vehicleIcon.tempFilePath,
    {
      public_id: `${brand} ${name} icon`,
      use_filename: true,
      folder: "Vehicles",
    }
  );
  fs.unlinkSync(req.files.vehicleIcon.tempFilePath);
  const frontImage = await cloudinary.uploader.upload(
    req.files.frontImage.tempFilePath,
    {
      public_id: `${brand} ${name} front image`,
      use_filename: true,
      folder: "Vehicles",
    }
  );
  fs.unlinkSync(req.files.frontImage.tempFilePath);
  const backImage = await cloudinary.uploader.upload(
    req.files.backImage.tempFilePath,
    {
      public_id: `${brand} ${name} back image`,
      use_filename: true,
      folder: "Vehicles",
    }
  );
  fs.unlinkSync(req.files.backImage.tempFilePath);
  const sideImage = await cloudinary.uploader.upload(
    req.files.sideImage.tempFilePath,
    {
      public_id: `${brand} ${name} side image`,
      use_filename: true,
      folder: "Vehicles",
    }
  );
  fs.unlinkSync(req.files.sideImage.tempFilePath);
  const interiorImage = await cloudinary.uploader.upload(
    req.files.interiorImage.tempFilePath,
    {
      public_id: `${brand} ${name} interior image`,
      use_filename: true,
      folder: "Vehicles",
    }
  );
  fs.unlinkSync(req.files.interiorImage.tempFilePath);
rur96b6h

rur96b6h1#

我一直在使用Cloudinary相当一段时间了,现在有一个类似的查询,你关于批量上传。据我所知,你不能通过一个请求将多个资产上传到Cloudinary。但是,您可以使用循环来改进当前代码,以避免代码重复。
如果你想上传的所有图片都在一个目录下,你可以运行下面的Node.js代码:

// Import packages
const fs = require('fs');
const cloudinary = require('cloudinary').v2;

// Replace with your credentials to configure Cloudinary
cloudinary.config({
  cloud_name: "cloud",
  api_key: "key",
  api_secret: "secret"
});

// Function to upload multiple images
const uploadMultipleImages = async (directoryPath, batchID) => {
  try {
    const fileNames = await fs.promises.readdir(directoryPath); // Read the file names from the specified directory

    const uploadResults = await Promise.all(
      fileNames.map(async (fileName) => {
        const imagePath = `${directoryPath}/${fileName}`; // Build the full path of each image file
        return cloudinary.uploader.upload(imagePath, {
          use_filename: true,
          tags: `batch ${batchID}` // Add a tag to identify the batch of uploaded images
        });
      })
    );

    // Process the upload results
    uploadResults.forEach((result) => {
      console.log(`Image uploaded with public ID: ${result.public_id}`);
      console.log(`Image URL: ${result.secure_url}`);
      console.log('----------------------');
    });
  } catch (error) {
    console.error('Error:', error);
  }
};

// Usage example
const directoryPath = 'asset_directory';
const batchID = 1;
uploadMultipleImages(directoryPath, batchID);

正如上面的代码所做的那样,我觉得用批号标记一组上传总是很有帮助的,这样可以在Cloudinary媒体库中更容易地跟踪。

xbp102n0

xbp102n02#

没有办法批量上传图像,但我找到了一个合适的方法来避免代码重复。
在这里,所有你需要创建一个函数,它是适合保存在其他文件,然后导入

const uploadImage = async (req, id, folder, title) => {
  const image = await cloudinary.uploader.upload(req.files[id].tempFilePath, {
    public_id: `${title}`,
    use_filename: true,
    folder: `${folder}`,
  });
  fs.unlinkSync(req.files[id].tempFilePath);
  return image;
};

每当你想上传一张图片时,只需调用函数并给予函数一个名字,因为你需要一个图片的URL

const thumbnail = await uploadImage(
    req,
    "thumbnail",
    "Vehicles",
    `Vehicle thumbnail`
  );

您可以访问图像链接如下

thumbnail = thumbnail.secure_url;

相关问题