You need to enable JavaScript to run this app. Node.js 如何为 Cloudinary 上传的图片配置自定义存储文件夹路径
优惠活动
大模型
产品
解决方案
定价
更多

Node.js 如何为 Cloudinary 上传的图片配置自定义存储文件夹路径

实现指定文件夹存储的代码调整方案

调整逻辑

Cloudinary 的上传接口在调用时,可通过第二个参数传入配置对象,使用folder字段指定资源存储的目标路径,即可实现文件归属到已创建的UserAvatar文件夹下,原有业务逻辑无需改动。

调整后的完整代码

router.post("/upload/image", function (req, res, next) {
  const dUri = new Datauri();

  const dataUri = (req) =>
    dUri.format(path.extname(req.name).toString(), req.data);

  if (req.files !== undefined && req.files !== null) {
    const { file, id } = req.files;

    const newFile = dataUri(file).content;

    cloudinary.uploader
      // 新增上传配置,指定存储文件夹
      .upload(newFile, {
        folder: "UserAvatar"
      })
      .then((result) => {
        const imageUrl = result.url;
        const data = { id: req.body.id, imageUrl };
        updateAvatar(data);
        return res.status(200).json({ message: "Success", data: { imageUrl } });
      })
      .catch((err) =>
        res.status(400).json({ message: "Error", data: { err } })
      );
  } else {
    return res.status(400).json({ message: "Error" });
  }
});

效果验证

调整后上传生成的资源URL会自动匹配目标路径结构,和预期一致:

https://res.cloudinary.com/teammateme/image/upload/v1617941466/UserAvatar/zwpbarfxvd94olczjjpa.png

补充说明

  • 若需要多层嵌套文件夹结构,直接在folder参数中传入层级路径即可,例如folder: "UserAvatar/2024/active"可将文件存入对应嵌套路径下。
  • 你在Cloudinary控制台已创建的UserAvatar文件夹会自动被配置关联,无需额外创建逻辑。

内容的提问来源于stack exchange,提问作者nathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.26 10:27:04