I am trying to upload an image along with its data. I am using multer to upload the image. But I keep getting error message like this:
{
[Error: ENOENT: no such file or directory, open 'D:\works\fiverr-kiddiemmerce-be\assets\products\2019-09-13T16:18:26.393Z180911-Naver-x-Dispatch-Yeoreum-cosmic-girls-wjsn-41821990-2000-1333.jpg']
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path:
'D:\\works\\fiverr-kiddiemmerce-be\\assets\\products\\2019-09-13T16:18:26.393Z180911-Naver-x-Dispatch-Yeoreum-cosmic-girls-wjsn-41821990-2000-1333.jpg',
storageErrors: []
}
How can I fix this? I have no clue at all. This is what i have done so far.
multer.js
const fs = require('fs');
const multer = require(`multer`);
const path = require(`path`);
const productPath = path.join(__dirname, `../../assets/products`);
const storage = multer.diskStorage({
destination: (req, file, cb) => {
if (file.fieldname.includes(`material_image`)) {
cb(null, materialPath);
} else if (file.fieldname.includes(`product_image`)) {
if (!fs.existsSync(productPath)) {
fs.mkdir(productPath, { recursive: true }, (err) => {
console.log(err);
});
}
cb(null, productPath);
}
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + file.originalname);
},
});
const filter = (req, file, cb) => {
if (file.mimetype === `image/png` || file.mimetype === `image/jpeg`) {
cb(null, true);
} else {
cb(null, false);
}
};
module.exports = {
upload: multer({
storage : storage,
limits : { fileSize: 720 * 1280 * 5 },
fileFilter : filter,
}),
};
and this is the productController.js (where I want to upload the image)
const { upload } = require(`../utils/multer`);
const multer = require(`multer`);
module.exports = {
store: async (req, res) => {
const img_upload = upload.any();
img_upload(req, res, (err) => {
if (err instanceof multer.MulterError) {
res.end();
return;
} else if (err) {
console.log(`It always goes here`);
console.log(err);
res.end();
return;
}
// Do something if no error
});
}
}
In windows you can't create files with colon :
, so you have to replace colon with dash new Date().toISOString().replace(/:/g , "-")
or change it to timestamp by adding Date.now()
instead of new Date().toISOString()