首页 > 解决方案 > 使用 node.js 的 Cloudinary 上传图片和视频需要太多时间

问题描述

我正在构建一个 mern 堆栈应用程序,用户可以根据他选择的类型上传多个图像或 1 个视频。我正在将文件上传到 cloudinary,但上传时间太长,我读到了 cloudinary 中的 notification_url,它会在操作完成时发送一个发布请求,但我不明白如何使用它。这是我没有通知 URL 的代码

async (req, res) => {
  let { content, type, title, tags, location } = req.body;
  if (req.files.length === 0 && type != "blogs") {
    return res
      .status(400)
      .json({ errors: [{ msg: "No files were uploaded." }] });
  }
  // console.log(req.files);
  try {
    const fileUrls = [];
    const filePublicIds = [];
    const optionsObj =
      type === "vlogs"
        ? {
            resource_type: "video",
            public_id: "videos",
          }
        : { public_id: "images" };
    for await (const file of req.files) {
      const result = await v2.uploader.upload(file.path, optionsObj);
      const { secure_url, public_id } = result;
      fileUrls.push(secure_url);
      filePublicIds.push(public_id);
    }
    const user = await User.findById(req.user.id).select("-password");
    content = type === "blogs" ? content : fileUrls;
    const public_id = type === "blogs" ? [] : filePublicIds;
    // console.log(content, public_id);
    const newPost = new Post({
      content,
      public_id,
      type,
      title,
      tags,
      location,
      user,
    });
    const post = await newPost.save();
    return res.json({ post });
    // console.log(result);
  } catch (e) {
    res.status(500).json({ errors: [{ msg: "Internal server error" }] });
  }
}

当 Cloudinary 将 POST 请求发送回我的服务器时,我是否应该创建另一个端点来更新内容和 public_id 数组?问题是,我需要知道要更新的帖子的 ID,但 cloudinary 不会将其发回。请建议我应该做什么

标签: reactjsmongodbexpressmerncloudinary

解决方案


推荐阅读