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));
}
});
Related
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 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);
});
}
},
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.
I am quite new in Node.js and express framework.
I wanted to create a service to upload file where it will display the image if the file type is an image. If the file is not an image it suppose to display error message to the user. I am using multer to upload file and if the file extension doesnt match with any of the predefined extension, it will return false to stop the upload process. But somehow it doesnt redirect the page to the error page if the upload stopped. Does the return false stopped the entire POST process? Is there any way for me to display error message if the upload stopped?
module.exports=function(app)
{
var express=require('express');
var multer=require('multer');
var path=require('path');
var fs=require('fs');
var bodyParser=require('body-parser');
var done = false;
var targetPath="";
app.use(bodyParser.urlencoded({uploadDir: '/uploads',extended:true, keepExtensions:true}));
app.use(function(req,res,next)
{
var handler = multer({ dest: './uploads/',
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
if(file.extension != 'png' && file.extension != 'jpg' && file.extension != 'jpeg' && file.extension != 'gif')
{
done = false;
return false;
}
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
targetPath = file.path;
done = true;
}
});
handler(req, res, next);
});
app.get('/',function (req,res)
{
res.render('newindex.jade')
});
app.get('/errorpage', function (req,res)
{
res.render('errorpage.jade')
})
app.post('/uploads', function (req,res)
{
if(done = true)
{
console.log(req.files);
//res.end("Image has been uploaded at " + targetPath);
res.redirect("/" + targetPath);
targetPath="";
//res.send('<img src="' + targetPath + '">');
}
else
{
res.redirect("./errorpage")
}
});
app.get('/uploads/:file', function (req, res)
{
file = req.params.file;
var img = fs.readFileSync("./" + "/uploads/" + file);
res.writeHead(200);
res.end(img, 'binary');
});
}
I think that you can add req, res in onFileUploadStart() and insert res.doSomething() before the line "return false;". For example:
onFileUploadStart: function (file, req, res) {
{
done = false;
res.json({message: "Upload failed"})
return false;
}
console.log(file.originalname + ' is starting ...')
}