Error no such file or directory, multer package - node.js

Getting this error in postman while uploading an image through multer
{
"error": {
"message": "ENOENT: no such file or directory, open 'D:\\adarsh\\API\\uploads\\2022-11-29T17:23:07.574Zdownload1.jpg'"
}
}
Code of it.
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
}
});
const upload = multer({storage: storage});
Tried writing the above code

The problem might be the way you are providing the destination path, try with '/uploads'

Related

multipart file upload not working using multer's diskStorage

nodejs
I am using multer to upload file in nodejs. The below code seems to work fine.
const upload = multer({ dest: "uploads/" });
But the code below doesn't work.
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads/");
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
Any idea on how to solve it?

Nodejs express multer file upload + path contains double slashes

I'm trying to upload an image to my directory using Postman. I am using Nodejs and multer as a middleware.
However, I get an ENOENT error:
My question is as follows, why does my code give double \\, and what can I do to change double backslashes to forward slash in the pathname?
My code so far is:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '.test/');
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
router.post('/', upload.single('productImage'), (req, res, next) => {
console.log(req.file);
...
...
...
I have tried using the .replace() method without any success.
const multer = require('multer');
let destination = '.uploads/';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, destination.replace('\\','/'));
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
I have also tried searching similar posts here on StackOverflow, e.g trying this posts answer Error: ENOENT: no such file or directory,
You can use path.normalize('\\dsgsd\\sdgsdg') method. You can find it in official NodeJS documentation https://nodejs.org/api/path.html#path_path_normalize_path
const multer = require('multer');
const { normalize } = require('path')
let destination = '.uploads/';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, normalize(destination));
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
I found the answer after a bit of googling.
The problem was not the double \\, they are allowed, the problem was in the way the filename was saved. The filename was of a datestring, and was saved in the format: 2020-11-25T12:15something, the problem is that Windows OS does not accept files with the character ":".
Solution would be to replace this line of code :
cb(null, new Date().toISOString() + file.originalname);
with
cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname);
Original answer here

How can I upload a zip file using nodejs and extract it?

I want to upload a zip file into the server using node.So can any one help me to figure it out.
First upload your zip file using Multer:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
Then unzip it using unzipper module:
1) Install unzipper module
npm i unzipper
2) ExtractZip.js JavaScript
const unzipper = require('./unzip');
var fs = require('fs');
fs.createReadStream('path/to/archive.zip')
.pipe(unzipper.Parse())
.on('entry', function (entry) {
const fileName = entry.path;
const type = entry.type; // 'Directory' or 'File'
const size = entry.vars.uncompressedSize; // There is also compressedSize;
if (fileName === "this IS the file I'm looking for") {
entry.pipe(fs.createWriteStream('output/path'));
} else {
entry.autodrain();
}
});
// Source
Test:
c:\Samim>node ExtractZip.js
You can try multer
npm install --save multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })

Multer - handle missing file

I'm using multer as express middleware to upload a file like so:
const upload = multer().single('fieldName');
router.post(
'/',
upload,
(req, res) => {
console.log(req.file)
}
);
It works fine except when I sent the form without a file. Then apparently the upload middleware is just skipped and req.file is undefined.
I tried to add a filter like so but apparently the filter function is not called when there is no file:
function fileFilter(req, file, cb) {
console.log('filtering'); //never reached when file is missing
if (!file) {
return cb(new Error('no file', false));
}
cb(null, true);
}
const upload = multer({fileFilter: fileFilter}).single('fieldName');
router.post(...)
Is there any way to handle the missing file inside the multer middleware? Or do I have to check afterwards?
check in you html form "fieldName" in input name
and this can you help
in you routes app
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+'.mp3')
}
})
var upload = multer({ storage: storage })
router.post(
'/uploadfile',upload.single('fieldName'),
)

multer save image without mimetype

I'm using "multer": "^1.0.6", And i Want to save image in upload folder.
My code is
app.post('/post', multer({dest: './uploads/'}).single('file'), function (req, res) {
response = {
message: 'File uploaded successfully',
filename: req.file.filename
};
res.end(JSON.stringify(response));
});
But I Have the file with this name in upload folder 8e6e425f8756e0bafb40ed1a3cb86964
Why I have this name without mimetype?
Multer saves files without extensions you can read this on GitHub:
filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.
If you want to save with the extension that you write your code like here:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname); // modified here or user file.mimetype
}
})
var upload = multer({ storage: storage })
All information you can find here https://github.com/expressjs/multer/blob/master/README.md
Multer not worried about the extension of the file and leave it completely on your side: you have to define itself a function that will do it. For example, like this:
var multer = require('multer');
var upload = multer({ storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
var ext = require('path').extname(file.originalname);
ext = ext.length>1 ? ext : "." + require('mime').extension(file.mimetype);
require('crypto').pseudoRandomBytes(16, function (err, raw) {
cb(null, (err ? undefined : raw.toString('hex') ) + ext);
});
}
})});
app.post('/post', upload.single('file'), function (req, res) {
response = {
message: 'File uploaded successfully',
filename: req.file.filename
};
res.end(JSON.stringify(response));
});

Resources