How to upload video in node js - 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.

Related

Cannot trim exceljs cell value

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.

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 can I decrease the image uploading time when using multer(nodejs multer) and AWS S3

I am hongkevin developing one service for photographers and models by using Node.js, MongoDB, and AWS.
For developing the photo upload function, I am using three modules such as multer, multer-s3, aws-sdk. The process is as followed.
Getting single image and related information from the client.
Upload it to AWS s3 by using multer.
Fint out whether the user is model or photographer.
Save the file information including the image url.
Unfortunately, I found that when uploading the image, it takes time from 1 second to 5 seconds.
Therefore, I want you to let me know how to decrease the time-consumption(how to give client the result within short time).
Thanks. My code is as followed.
var express = require('express');
var router = express.Router();
var db = require('../models/db');
require('../models/bookmodel');
require('../models/usermodel');
var BookModel = db.model('Book');
var UserModel = db.model('User');
// 이미지 업로드 셋팅
var multer = require('multer');
var multerS3 = require('multer-s3');
var AWS = require('aws-sdk');
AWS.config.region = 'ap-northeast-1';
var s3 = new AWS.S3();
var upload = multer({
storage: multerS3({
s3 : s3,
bucket : 'mocatest',
acl : 'public-read',
key : function(req, file, callback) {
var tmp = file.mimetype.split('/')[1]; // file.mimetype
if (tmp == 'jpeg') { tmp = 'jpg' }
var ext = "." + tmp;
var keyword = "Moca_Photo_";
var newname = keyword + Date.now().toString() + ext;
callback(null, newname);
}
})
});
// 3-11. Uploading a book(사진 업로드하기)
router.post('/', upload.single('img'), function(req, res, next) {
var token_user_id = req.decoded.user_id;
// imgSave function start
var imgSave = function() {
var book_img = req.file.location;
var book_desc = req.body.book_desc;
var data = new BookModel({
user_id : token_user_id,
book_img : book_img,
book_desc : book_desc
});
data.save(function(err, docs) {
if (err) { return next(err); }
res.json({ success: 1, message: "photo is uploaded" });
});
};
// imgSave function end
UserModel.findOne({ user_id: token_user_id }, function(err, docs) {
if (err) { return next(err); }
if (docs.user_type == "M" || docs.user_type == "P") {
imgSave();
} else {
res.json({ success: 0, message: "You should be registered as a model or photographer first" });
}
});
});

Redirect page after upload stopped using Nodejs and multer

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 ...')
}

Resources