I'm uploading images on the server and when I get the images in Express js using Multer, I'm not able to rename them with a progressive number like:
nameImage_1.jpg
nameImage_2.jpg
nameImage_3.jpg
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./assets/img/products/");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
some ideas ??
THX
I don't know if this will help you but I have it like this
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/csvs/");
},
filename: (req, file, cb) => {
console.log(file.originalname);
cb(null, `${Date.now()}-name-${file.originalname}`);
},
});
Related
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?
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
I am using multer to upload file in my application.
like: https://github.com/expressjs/multer/blob/master/README.md
Can path traversal vulnerability possible ? If yes then tell us how we can stop this?
Currenlty, I am using below code. I just want to confirm, Is there any file vulnerable risk? Please comment.
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
console.log(file);
var ext = file.originalname.split('.').pop();
cb(null, Date.now() + '_' + file.originalname);
}});
const fileFilter = (req, file, cb) => {
// Accept or reject the file based on if MIME type is found in accepted list
if (acceptedMimeTypes.indexOf(file.mimetype) < 0) {
return cb("エラー:このタイプのファイルはアップロードできません。ZIP形式とLZH形式のファイルのみアップロードしてください。", false) // Error: You can't upload files of this type. Please upload images and zips only.
}
else {
return cb(null, true);
}
}
var upload = multer({ storage: storage, fileFilter: fileFilter, limits: { fileSize: 1024 * 1024 * 1 } }).single('file');
If there is any risk then please suggest me a better approach with expressjs multer.
You can modify the fileName using this code so no one can threaten you :
const storage = multer.diskStorage({
destination: './public',
filename(req, file, cb) {
cb(null, 'Your File Name');
},
});
and also you can make it dynamic using randomatic and time like this :
const storage = multer.diskStorage({
destination: './public',
filename(req, file, cb) {
cb(null, `${new Date().getTime()}`);
},
});
With fileupload we can get tempfilepath but with multer any way to get tempfile path?I want to upload files to cloudinary using temp file path.. Here is my code.
const storage = multer.diskStorage({
destination: (req, file, cb)=>{
cb(null, 'uploads')
},
filename: (req, file, cb)=>{
cb(null, Date.now() + file.originalname)
},
useTempFiles: true
})
const upload = multer({storage});
app.post("/upload", upload.single('photo'), (req, res, next)=>{
let fileinfo = req.file;
console.log(fileinfo);
cloudinary.uploader.upload(fileinfo.tempFilePath,{width: 70, height: 90, crop: "fit"}, (err,result)=>{
console.error(err);
console.log(result.url);
});
})
const storage = multer.diskStorage({
filename: (req, file, cb)=>{
cb(null, Date.now() + file.originalname)
}
})
const upload = multer({storage});
app.post("/upload", upload.single('photo'), (req, res,
next)=>{
let fileinfo = req.file;
console.log(fileinfo);
cloudinary.uploader.upload(fileinfo.path,{width: 70,
height: 90,crop: "fit"}, (err,result)=>{
console.error(err);
console.log(result.url);
});
})
Make this changes to your code and try this
Multer gives you access to the uploaded files before storing them.
If you want, however, to store files and access them like you do in PHP, you should use the DiskStorage option of the 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())
}
})
Both the arguments taken by the diskStorage are functions. One function determines the upload folder and the other one the file name.
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));
});