Search code examples
node.jsmulter

How to upload image to external folder using NodeJS multer


I am having trouble with the upload destination in nodejs using multer package. The image are uploading in the folder within nodejs. Bt i want to store that at a different Path outside the project root folder. Here is the below code

const imageURL = "http://localhost/demoAdmin/images/"; 

    const imageStorage = multer.diskStorage({
      destination: imageURL, // Destination to store image
      filename: (req, file, cb) => {
        cb(
          null,
          file.fieldname + "_" + Date.now() + path.extname(file.originalname)
        );
      },
    });

    const imageUpload = multer({
      storage: imageStorage,
      limits: {
        fileSize: 1000000, // 1000000 Bytes = 1 MB
      },
      fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(png|jpg)$/)) {
          // upload only png and jpg format
          return cb(new Error("Only images allowed"));
        }
        cb(undefined, true);
      },
    }).single("image");

    imageUpload(req, res, (err) => {
      if (err) {
        if (err.message) {
          return res.status(500).json({
            success: 0,
            msg: err.message,
          });
        }
        console.log()
        return res.status(500).json({
          success: 0,
          msg: "Only images allowed",
        });
      }
      res.status(200).json({
        success: 1,
        msg: req.file,
      });
    });

Any help from your side will be appreciated! Thanks.


Solution

  • The problem with your imageUrl variable is that it does not point to an absolute path on your server/host.

    You need to use the absolute path to the directory of the host/server you want to store images inside.

    For example:

    const imageURL = "/usr/tmp/demoAdmin/images/"; 
    

    Also, destination takes a function:

    destination: (req, file, callback) =>
          callback(null, imageUrl);
    }