Cannot trim exceljs cell value - node.js

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.

Related

Multer - Stop File Uploading If Form Validation Fails

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.

Upload photo into a folder in nodejs

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));
}
});

How to resize the image before saving to server for Node JS. (multer itself, gm) I am open to any option

I tried to include image resizing before posting. Multer is used to receiving photos. Then, after using input all information including photos.
I would like to reduce the size and quality of image before they post. However, it's doesn't work. Anyone can giving suggestion?
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'photo')
},
filename: function (req, file, cb) {
cb(null, 'car-' + Date.now() + '.png')
},
})
const upload = multer({ storage: storage })
const gm = require('gm');
module.exports = (app,passport) => {
app.post('/sell', isLoggedIn, upload.any(), (req,res,next) => {
gm(req.files)
.resize(250, 250)
.gravity('Center')
.extent(width, height)
.noProfile()
.write('/photo/' + req.file.fieldname + '-' + Date.now())
async.waterfall([
function(callback) {
var newCar = new Car();
newCar.owner = req.user._id;
newCar.make = req.body.make;
newCar.model = req.body.model;
newCar.year = req.body.year;
newCar.mileage = req.body.mileage;
newCar.price = req.body.price;
newCar.detail = req.body.detail;
newCar.locationProvince = req.body.locationProvince;
newCar.locationDistrict = req.body.locationDistrict;
//newCar.image = req.files;
newCar.save((err) => {
callback(err, newCar);
});
},
function (newCar, callback) {
User.update (
{
_id: req.user._id
},{
$push: {cars: newCar._id }
}, function (err,count) {
req.flash('success', 'success')
res.redirect('/')
}
)
}
]);
});
}
Firstly, please specifies error or something more about your problem. I think you need to console.log -> res.files, it could be an array. Also, check your path in write if it's correct. And the last one, probably you don't add callback function -> write(path, cb).
I can solve it now. But, I don't know how to save the image which have been resized to mongoose.
app.post('/sell', isLoggedIn, upload.any(), (req, res, next) => {
async.waterfall([
function(callback) {
console.log('files', req.files)
if (req.files.length > 0) {
req.files.map(function(file) {
var x = gm(file.path)
.resize(800, 640)
.gravity('Center')
//.extent(250, 250)
.noProfile()
.quality(80)
.write('./photo/resized/' + file.filename +'-800x640', function(err) {
if (err) {
console.log('error : ', err)
}
console.log(file.filename + ' resized!')
});
})
//console.log(req.files.path)
//console.log(req.files)
var newCar = new Car();
newCar.owner = req.user._id;
newCar.make = req.body.make;
newCar.model = req.body.model;
newCar.year = req.body.year;
newCar.mileage = req.body.mileage;
newCar.price = req.body.price;
newCar.detail = req.body.detail;
newCar.locationProvince = req.body.locationProvince;
newCar.locationDistrict = req.body.locationDistrict;
newCar.image = req.files;
newCar.image_resized = x;
newCar.save((err) => {
callback(err, newCar);
});
}
},

How to upload video in node js

I am trying to upload video in node js and i have some doubts related.Is image upload and video upload are same i.e the code for image upload work for video upload?
Here is my code,
exports.uploadVideo = function( req, res ) {
upload_image = '';
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
var obj = req.body;
obj.video = upload_image;
if(obj.edit){
delete obj.edit;
updateBlog(req, res, obj, 'update');
} else {console.log('hi')
addVideo(req, res, obj);
}
});
};
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, config.videoUploadPath);
},
filename: function (req, file, callback) {
var ext = '';
var name = '';
if(file.originalname){
var p = file.originalname.lastIndexOf(".");
ext = file.originalname.substring(p+1);
var firstName = file.originalname.substring(0, p+1);
name = firstName + '-' + Date.now();
name += '.'+ext;
}
upload_image += name;
upload_image += ',';
upload_image = upload_image.replace(' ', '');
callback(null, name);
}
});
var upload = multer({ storage : storage}).array('video');
According to my routes,exports.uploadVideo() is called first.I am completely new to this,can anyone please help me.Thanks.

How set a function into limits parameters on multer?

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();
};

Resources