'Multer does not find the folder that does exist to save images
I am trying to upload images using Multer and although the destination folder does exist Multer tells me the error that it cannot find the folder, this is my code:
import { Router } from 'express';
import { check, validationResult } from 'express-validator';
const path = require('path');
const multer = require('multer')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../uploads/'))
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname)
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/png" || file.mimetype === "image/jpg" || file.mimetype === "image/jpeg") {
cb(null, true);
} else {
cb(null, false);
return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
}
};
const upload = multer(
{
storage: storage,
limits:{
fileSize: 1024 * 1024
},
fileFilter: fileFilter
})
let router = Router();
router.post('/', upload.single('img'),
newProduct
);
But when doing the test from Postman it tells me the error:
Error: ENOENT: no such file or directory, open 'C:\project\uploads\2022-02-11T03:17:32.711Zcloud.png'
The strange thing is that the folder path does exist:
And more strange is that if I use the basic code of multer without using multer.diskStorage if I can save in the folder in this way:
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
I really don't know why when using simply if it shows the path that exists but multer can't find the directory even though it exists.
Thanks.
Solution 1:[1]
I changed this line:
cb(null, new Date().toISOString() + file.originalname)
By this line:
cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
Replacing the colon with a hyphen means that windows doesn't seem to understand colon paths properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |

