1

I'm new in using nodejs and multer and I want to upload an image but in two different directories. I tried using two different middleware but since the first multer function returns a file destination I couldnt use it to upload in the other multer function. Is it possbile to upload a file using multer in two different directories?

1 Answer 1

2

Create multiple storages and call them at the same time.

Example:

const app = require("express")();
const multer = require('multer');

const storageA = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './storageA/');
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }
});

const storageB = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './storageB/');
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }
});

const destA = multer({ storage: storageA });
const destB = multer({ storage: storageB });

function fileUpload(req, res, next) {
  destA.single('file')(req, res, next);
  destB.single('file')(req, res, next);
}

app.post("/", fileUpload, (req, res) => {
  res.json({ file: req.file });
});


app.listen(3000, () => {
  console.log("Server started");
});

The uploaded file will be store in ./storageA and ./storageB.

This is not an official way, but went I try it, it works!

Sign up to request clarification or add additional context in comments.

1 Comment

thanks this works on local. Now Ill try to implement this on s3 and google drive!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.