基于表单字段数据的上传目录很强大?

Upload directory based on the form fields data in formidable?

上传文件(项目实体的图像)时,我想在 /public/images 中为每个项目 ID 创建一个新的 Linux 子目录以存储其图像。但是图像会立即保存进入提供的目录,然后我才能指定项目 ID(在请求中)。有没有办法用 formidable 或 multer 做到这一点?

    // Upload Image
    router.post("/project_image", function(req, res, next) {

      const form = new IncomingForm({
        uploadDir: process.cwd() + "/public/images", // <- e.g. I would like this to be `/public/images/${req.body.project_id}`
        keepExtensions: true
      });
      form.parse(req);
      let project;

      form.on("field", (name, value) => {
        project = JSON.parse(value);
      });

      form.on("file", (field, file) => {

        let path = file.path;
        let fileName = path.substr(path.lastIndexOf("upload"));

        return req.db
          .from("projects")
          .where("id", "=", project.project_id)
          .update({ image: "/images/" + fileName })
          .then(() => {
            return res.status(200).json({
              message: "Image Upload Successful",
              error: false
            });
        })

      form.on("end", () => {});

    });

谢谢。

我自己用下面的方法解决了。基本上我将文件移动到它的预定目的地。

    // Upload Image
    router.post("/project_image", function(req, res, next) {
      const directory = process.cwd() + "/public/images";
      const form = new IncomingForm({
        uploadDir: directory, 
        keepExtensions: true
      });
      form.parse(req);
      let project;

      form.on("field", (name, value) => {
        project = JSON.parse(value);
      });

      form.on("file", (field, file) => {

        let path = file.path;
        let fileName = path.substr(path.lastIndexOf("upload"));
        let destinationPath = directory + `/${project.project_id}/`;

        if (fs.existsSync(destinationPath)) {
          moveFile(path, destinationPath);
        } else {
          fs.mkdirSync(directory + `/${project.project_id}/`);
          moveFile(path, destinationPath);
        }

        return req.db
          .from("projects")
          .where("id", "=", project.project_id)
          .update({ image: "/images/" + fileName })
          .then(() => {
            return res.status(200).json({
              message: "Image Upload Successful",
              error: false
            });
        })

      form.on("end", () => {});

    });
};