After this question:
CanI upload many files in different folder using multer and a single html form?
I set multer parameters dinamically and the code works on: destination, filename and filter but not on "limits" parameters!
Someone can help me?
var path = require('path');
var multer = require('multer');
var defaultMaxSize = 3 * 1024 * 1024;
var defaultFiles = 1;
exports.upload = function(obj, next) {
var upld = {};
var storage = {};
var limits = {};
for (key in obj) {
switch (key) {
case 'destination':
storage.destination = function(request, file, cb) {
cb(null, obj.destination[file.fieldname]);
};
break;
case 'filename':
storage.filename = function(request, file, cb) {
if (obj.filename[file.fieldname] != undefined) {
nome = obj.filename[file.fieldname];
if (nome == undefined)
nome = file.originalname.substring(0, file.originalname.lastIndexOf("."));
nome += file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
} else nome = file.originalname.split('/').pop().trim();
cb(null, nome);
};
break;
case 'FieldNameSize':
limits.fieldNameSize = function(request, file, cb) {
if (obj.fieldNameSize[file.fieldname] != undefined)
cb(null, obj.fieldNameSize[file.fieldname]);
else return cb(null, true);
};
break;
case 'fieldSize':
limits.fieldSize = function(request, file, cb) {
if (obj.fieldSize[file.fieldname] != undefined)
cb(null, obj.fieldSize[file.fieldname]);
else return cb(null, true);
};
break;
case 'fields':
limits.fields = function(request, file, cb) {
if (obj.fields[file.fieldname] != undefined)
cb(null, obj.fields[file.fieldname]);
else return cb(null, true);
};
break;
case 'fileSize':
limits.fileSize = function(request, file, cb) {
if (obj.fileSize[file.fieldname] != undefined)
cb(null, obj.fileSize[file.fieldname]);
else return cb(null, true);
};
break;
case 'files':
limits.files = function(request, file, cb) {
if (obj.files[file.fieldname] != undefined)
cb(null, obj.files[file.fieldname]);
else return cb(null, true);
};
break;
case 'parts':
limits.parts = function(request, file, cb) {
if (obj.parts[file.fieldname] != undefined)
cb(null, obj.parts[file.fieldname]);
else return cb(null, true);
};
break;
case 'filetypes':
upld.fileFilter = function(req, file, cb) {
if (obj.filetypes[file.fieldname] != undefined) {
var f = obj.filetypes[file.fieldname];
f = f.replace(",", "|");
var re = new RegExp(f);
var mimetype = re.test(file.mimetype);
var extname = re.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb("Sono Accettate solo le seguenti estensioni: " + obj.filetypes[file.fieldname]);
} else return cb(null, true);
};
break;
}
}
if (storage.filename == undefined)
storage.filename = function(request, file, cb) {
nome = file.originalname.split('/').pop().trim();
cb(null, Date.now() + "_" + nome);
};
if (limits.fileSize == undefined)
limits.fileSize = defaultMaxSize;
/*
var maxSize=l.maxSize;
limitsfileSize= function (request, file, cb) {
if(file.size>(maxSize)) { cb(null,true); }
else { cb("Il file non può pesare più di"+maxSize+" MB" ); }
};
*/
upld.storage = multer.diskStorage(storage);
upld.limits = limits;
return multer(upld).any();
};
Related
const multer = require('multer');
// Define file storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads');
},
filename: function (req, file, cb) {
cb(
null,
new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname
);
},
});
// Specify file format that can be saved
function fileFilter(req, file, cb) {
if (
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) {
cb(null, true);
} else {
cb(null, false);
}
}
const upload = multer({ storage, fileFilter });
// File Size Formatter
const fileSizeFormatter = (bytes, decimal) => {
if (bytes === 0) {
return '0 Bytes';
}
const dm = decimal || 2;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'YB', 'ZB'];
const index = Math.floor(Math.log(bytes) / Math.log(1000));
return (
parseFloat((bytes / Math.pow(1000, index)).toFixed(dm)) + ' ' + sizes[index]
);
};
module.exports = { upload, fileSizeFormatter };
I want to get values from an Excel file :
var Excel = require("exceljs");
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../config/uploads/'));
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });
router.post("/affecterConducteur", upload.single('fichier'), function(req, res) {
var filename = req.file.destination + req.file.filename;
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename).then(function() {
var sheet = workbook.getWorksheet(1);
for(var r=2; r<=sheet.rowCount; r++) {
var row = sheet.getRow(r);
var msisdn = row.getCell(1).value, immatriculation = row.getCell(2).value;
if (msisdn != null) {
msisdn = msisdn.trim();
msisdn = (msisdn.substr(0,3) == "034" ? msisdn : "0".concat(msisdn));
immatriculation = immatriculation.trim();
immatriculation = immatriculation.replace(/ /g, "");
var sql = "insert into "+db.getPrefixNomTables()+"conducteur(type_conducteur_id, msisdn) "+
"values((select type_conducteur_id from "+db.getPrefixNomTables()+"type_conducteur where lower(type_conducteur_lib) = 'cdz'), '"+msisdn+"')";
connexion.query(sql, function(err, rows) {
if (err)
throw err;
var maj = "update "+db.getPrefixNomTables()+"vehicule "+
"set conducteur_id = "+rows.insertId+" where replace(immatriculation, ' ', '') = '"+immatriculation+"'";
connexion.query(maj, function(err2, rows2) {
if (err2)
throw err2;
});
});
}
}
res.send("");
});
});
At runtime I get TypeError: msisdn.trim is not a function. So what is wrong ?
You may want to check that msisdn is a string instead of checking that it's not null.
if(typeof msisdn === 'string')
It's complaining that trim isn't a function because you are trying to perform it on something that isn't a string.
i have mixed form with file upload and normal form fields, and while sending this form to Nodejs server i am validating form but problem is that i do not know how to stop uploading the file if (for example) one of the form field is empty.
so for example:
if(name.trim().length < 1){
//stop uploading of file
return res.status(409).send({
message: 'provide name'
})
}
how can i do that (Multer & ExpressJS)?
I was using following code in my case (node & express).
From routes.js file I am calling this insertRating method. like below
//routes.js
router.post('/common/insertrating',RatingService.insertRating);
//controller class
// storage & upload are configurations
var storage = multer.diskStorage({
destination: function (req, file, cb) {
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var year = dateObj.getUTCFullYear();
console.log("month and yeare are " + month + " year " + year);
var quarterMonth = "";
var quarterYear = "";
var dir_path = '../../uploads/' + year + '/' + quarterMonth;
mkdirp(dir_path, function (err) {
if (err) {
console.log("error is cominggg insidee");
}
else {
console.log("folder is createtd ")
}
cb(null, '../../uploads/' + year + '/' + quarterMonth)
})
console.log("incomingggg to destination");
},
filename: function (req, file, cb) {
console.log("incoming to filename")
cb(null, Date.now() + "_" + file.originalname);
},
});
var upload = multer({
storage: storage,
limits: {
fileSize: 1048576 * 5
},
fileFilter: function (req, file, callback) {
var ext = path.extname(file.originalname);
ext = ext.toLowerCase();
console.log("ext isss " + ext);
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg' && ext !== '.pdf' && ext !== '.txt'
&& ext !== '.doc' && ext !== '.docx' && ext !== '.xlsx' && ext !== '.xls'
) {
return callback(new Error('Only specific extensions are allowed'))
}
callback(null, true)
}
}).array('files', 5);
// calling below insertRating method from routes js file...
exports.insertRating = async function (req, res) {
let quarterData = req.query.quarterData;
quarterData = JSON.parse(quarterData);
if (quarterData != null) { // here you can check your custom condition like name.trim().length
req.files = []; // not required
upload(req, res, async function (err) { // calling upload
if (err) {
res.send("error is cominggg")
return;
} else {
res.send("file is uploaded");
}
//
});
}
else {
res.send("filed must not be empty");
}
}
You can simply throw error:
in express::
app.get("/upload-image", multterUpload.single("image"), (req, res, next)=>{
try{
if(name.trim().length < 1) {
throw new Error("name length is not valid");
//or
return res.status(409).json({msg: "failed"});
}
// you all operation ....
res.status(200).json({msg: "success"});
}cathc(e=>{
next(e)
});
})
this is something you can do or you can return something else instead of throwing an error.
I want to upload an image in a folder using nodejs but i don't know how to do it
Here is my insert in my ImageDao
exports.insert = function(data, callback){
console.log("in imagesDao insert");
var query = " insert into " + tableName + " (url,ajoute_par)";
query = query + " values(?,?);";
var values = [data.url , data.ajoute_par];
// var values = [encodeURIComponent(data.url) , data.ajoute_par];
database.execute(query, values, function(){
callback();
});
}
And here is my image controller
// insert
exports.write = function(request, response){
console.log("in images write");
// Get the data.
var postData = "";
request.on('data', function(data){ // request.on is a listener. Call when data can be read
postData = postData + data;
});
request.on('end', function(){ // Called when data has been read
var dataObj = JSON.parse(postData);
dao.insert(dataObj, function(){
send(response, '{"write result" : "Inserted successfuly"}');
});
});
}
To upload files you can use multer module of nodejs. https://github.com/expressjs/multer
images_storage: function () {
return multer.diskStorage({
destination: function (req, file, cb) {
mkdirp(Config.upload_images_path, function (err) {
});
cb(null, Config.upload_images_path)
}
,
filename: function (req, file, cb) {
var getFileExt = function (fileName) {
var fileExt = fileName.split(".");
if (fileExt.length === 1 || (fileExt[0] === "" && fileExt.length === 2)) {
return "";
}
return fileExt.pop();
}
cb(null, Date.now() + '.' + getFileExt(file.originalname))
}
});
},
// Image uploading
const fs = require('fs');
const multer = require('multer');
const Uploads = multer({
storage: utility.images_storage(),
fileFilter: function (req, file, cb) {
if (Config.image_format_arr.indexOf(file.mimetype))
cb(null, true);
else
cb(null, false);
}
});
//And in your route you can use the upload function
router.post('/upload-logo', Uploads.single('school_logo'), function (req, res, next) {
var school_id = req.body.school_id;
var result = {flag: false, message: "Error Occurred! in saving school logo."};
console.log("REQUEST FILES " + req.file);
// Save School Logo
if (typeof req.file != 'undefined' && req.file.size > 0) {
School.findByIdAndUpdate(school_id, {
$set: {
school_logo: req.file.filename
}
}, {'new': true}, function (err, school_details) {
console.log("school_details " + school_details);
if (!err && school_details) {
result.flag = true;
result.message = "School logo has been successfully updated";
result.path = '/uploads/images/' + school_details.school_logo;
//req.session.school_details = school_details;
utility.upgradeSchoolLogoSessionValue(school_details, false, function (updated_school_details) {
console.log("BEFOR SESSION IS UPDATED" + JSON.stringify(req.session.school_details));
req.session.school_details = updated_school_details;
console.log("SESSION IS UPDATED" + JSON.stringify(req.session.school_details));
});
console.log("FILE NAME IS THIS " + req.file.filename);
}
res.json(JSON.stringify(result));
});
}
else {
res.json(JSON.stringify(result));
}
});
I'm trying to develop a module that should upload files from a single html form.
Imagine a form that contains two files:
1) the avatar of the user;
2) the curriculum vitae the same user.
I would upload the first file in /avatar and the second in /cv.
I can use to do that three method:
.array('input file name');
.fields([{ name: 'avatar'},
{ name: 'curriculum'}]);
. any()
The first accepts many files but its must have the same fields name;
The second accepts many files and its can have the names passed (and I think it should be right road for me);
the third accepts all files all names I set on html form.
Well, its work well but the problem is that I don't know how set different folders for each file!
The last trial was:
app.route('/upload').post(.upload(fileObj1).array('avatar'),upload(fileObj2).array('curriculum'),function (request, response, next) {
but it returns:
Error: Unexpected field
The problem isn't in other parts of code because if I launch this
code:
app.route('/upload').post(.upload(fileObj1).array('avatar'),function
(request, response, next) {
passing a single file it works correctly!
Someone can help me?
I resolved myself!
This is my not perfect solution (it works well for destination, filename and filetypes but not for maxsize and files) however, I want share my code:
in app.js I create an object like this:
var obj={
destination: {input-name1:'./uploads', input-name:'./uplds'},
filename: { input-name1:'file1', input-name2:'file2'},
FieldNameSize:undefined,
fieldSize:undefined,
fields:undefined,
fileSize:{input-name1:2*1024*1024, input-name2:10*1024*1024},
files:{input-name1:3,input-name2:1},
parts:undefined,
filetypes:{input-name1:"jpeg,jpg"}
};
and in rules_upload.js:
var path = require('path');
var multer = require('multer');
var defaultMaxSize=3*1024*1024;
var defaultFiles=1;
exports.upload = function (obj, next) {
var upld = {};
var storage={};
var limits = {};
for (key in obj)
{
switch (key) {
case 'destination':
storage.destination= function (request, file, cb) {
cb(null,obj.destination[file.fieldname]);
};
break;
case 'filename':
storage.filename=function (request, file, cb) {
if(obj.filename[file.fieldname]!=undefined)
{
nome=obj.filename[file.fieldname];
if(nome==undefined)
nome=file.originalname.substring(0, file.originalname.lastIndexOf("."));
nome+=file.originalname.substring(file.originalname.lastIndexOf('.'),file.originalname.length);
}
else nome=file.originalname.split('/').pop().trim();
cb(null, nome);
};
break;
case 'FieldNameSize':
limits.fieldNameSize = function (request, file, cb) {
if(obj.fieldNameSize[file.fieldname]!=undefined)
cb(null,obj.fieldNameSize[file.fieldname]);
else return cb(null, true);
};
break;
case 'fieldSize':
limits.fieldSize= function (request, file, cb) {
if(obj.fieldSize[file.fieldname]!=undefined)
cb(null,obj.fieldSize[file.fieldname]);
else return cb(null, true);
};
break;
case 'fields':
limits.fields = function (request, file, cb) {
if(obj.fields[file.fieldname]!=undefined)
cb(null,obj.fields[file.fieldname]);
else return cb(null, true);
};
break;
case 'fileSize':
limits.fileSize = function (request, file, cb) {
if(obj.fileSize[file.fieldname]!=undefined)
cb(null,obj.fileSize[file.fieldname]);
else return cb(null, true);
};
break;
case 'files':
limits.files = function (request, file, cb) {
if(obj.files[file.fieldname]!=undefined)
cb(null,obj.files[file.fieldname]);
else return cb(null, true);
};
break;
case 'parts':
limits.parts = function (request, file, cb) {
if(obj.parts[file.fieldname]!=undefined)
cb(null,obj.parts[file.fieldname]);
else return cb(null, true);
};
break;
case 'filetypes':
upld.fileFilter= function (req, file, cb) {
if(obj.filetypes[file.fieldname]!=undefined){
var f=obj.filetypes[file.fieldname];
f=f.replace(",","|");
var re= new RegExp(f);
var mimetype = re.test(file.mimetype);
var extname = re.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname ) {return cb(null, true); }
cb("Sono Accettate solo le seguenti estensioni: " + obj.filetypes[file.fieldname]);
}
else return cb(null, true);
};
break;
}
}
if(storage.filename==undefined)
storage.filename= function (request, file, cb) {
nome=file.originalname.split('/').pop().trim();
cb(null, Date.now()+"_"+nome);
};
if(limits.fileSize==undefined)
limits.fileSize=defaultMaxSize;
/*
var maxSize=l.maxSize;
limitsfileSize= function (request, file, cb) {
if(file.size>(maxSize)) { cb(null,true); }
else { cb("Il file non può pesare più di"+maxSize+" MB" ); }
};
*/
upld.storage= multer.diskStorage(storage);
upld.limits=limits;
return multer(upld).any();
};