Search code examples
javascriptnode.jsexpressformidable

Upload directory based on the form fields data in formidable?


When uploading files (images for a Project entity) I would like to create a new Linux subdirectory in /public/images for each Project ID to store its images in. However the images are saved immediately into the directory provided before I can specify the Project ID (which is in the request). Is there a way to do this with formidable or perhaps 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", () => {});

    });

Thank you.


Solution

  • Solved it myself with the following. Basically I move the file to its intended destination.

        // 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", () => {});
    
        });
    };