Search code examples
node.jsdockerexpressmulter

Multer not uploading files to directory and no errors showing


I'm trying to get Multer to save images in an src/uploads directory. Everything seems to work fine with no errors but the src/uploads directory is empty after the endpoint is called.

I'm using a microservices architecture using Node, Express, and running it locally DockerDesktop + Kubernetes using Skaffold.

Here is my route:

const router = express.Router();

let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, './uploads'));
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});

let upload = multer({ storage });

router.post(
  '/api/products/images',
  upload.single('image'),
  async (req: Request, res: Response) => {
    console.log(req.file);
    res.status(201).send('success');
  },
);


export { router as imageRouterRouter };

My app file includes:

app.use(imageRouterRouter);
app.use('/uploads', express.static(__dirname));

I know I'm receiving the file successfully via postman, Multer is 'uploading' it and the path is correct as I'm logging the following req.file:

[products] {
[products]   fieldname: 'image',
[products]   originalname: 'cute-dog.jpeg',
[products]   encoding: '7bit',
[products]   mimetype: 'image/jpeg',
[products]   destination: '/app/src/uploads',
[products]   filename: 'cute-dog.jpeg',
[products]   path: '/app/src/uploads/cute-dog.jpeg',
[products]   size: 18473
[products] }

Any help would be much appreciated as I've spent a couple days on it with no luck. Thanks.


Solution

  • I figured out what the problem was.

    I was checking the src/uploads directory on my LOCAL machine, expecting it to contain the new files. But because I'm using docker, the new files were written to the container instead. Using the below, I explored the container and confirmed the files were there:

    docker exec -it <container_id> /bin/sh
    

    Hope this helps anyone else who is as silly as me.