Store an Image from registration page using NodeJS - node.js

I am using ExpressJS and NodeJS .
I build a registration page which require from the user to upload his image.
the code in Jade
.form-container
h1 Create a User
form(name="adduser",method="post",action="/adduser")
.col-xs-13
p Username
input.form-control(type="text", name="username")
.col-xs-13
p Email
input.form-control(type="text", name="useremail")
.col-xs-13
p Upload an Image
input.form-control(type='file', name ="pic", accept='image/*')
.col-xs-13
p Password
input#password.form-control(type='text', name='pass', required='')
.col-xs-13
p Confirm Password
input#confirm_password.form-control(type='text', required='' , onkeyup='checkPass(); return false;')
span#confirmMessage.confirmMessage
br
.form-group
button#myBtn.btn.btn-primary(type="submit") submit
i also have a script down there but its doesnt matter right now.
the thing is i want to save the image in my Express Project directory but i am not sure how to do that. here is the code which store the other information in Mongodb DB , i just need to save the image now.
/* POST to Add User Service */
router.post('/adduser', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
var userPass = req.body.pass;
var collection = db.get('users');
// Submit to the DB
collection.insert({
"username" : userName,
"email" : userEmail,
"password" : userPass
}, function (err, doc) {
if (err) {
res.send("There was a problem adding the information to the database.");
}
else {
res.redirect("userlist");
}
});
});

This might help you:
var express = require('express'),
app = express(),
formidable = require('formidable'),
util = require('util'),
fs = require('fs-extra'),
bodyparser=require('body-parser'),
qt = require('quickthumb'),
path = require('path');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db');
var Images = require('./model.js');
app.use(qt.static(__dirname + '/'));
app.use(bodyparser());
app.set('view engine','ejs');
app.post('/upload',function (req, res){
var form = new formidable.IncomingForm();
var userObj = [];
form.parse(req, function(err, fields, files) {
});
form.on('field',function(name,value){
// you will get the all the input field values here...
console.log(name,value);//name gives input field name and value gives input value
userObj.push({name:value});
});
form.on('end', function(fields, files) {
//You can save the data into collection from the array
//Images is my model
var img = new Images();
var temp_path = this.openedFiles[x].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[x].name;
//console.log('file '+file_name);
img.size = this.openedFiles[x].size;
img.type = this.openedFiles[x].type;
/* Location where we want to copy the uploaded file */
var new_location = 'uploads/';
//to copy the file into a folder
fs.copy(temp_path, new_location + file_name, function(err) {
if (err) {
console.log(err);
}
});//fscopy
});//form end
res.send('Done!!');
});//post
app.listen(3000);
console.log('started server');

For express use this.
var formidable = require('formidable');
npm i formidable
router.post("/one", (req, res) => {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(fields);
console.log(files);
res.send(files);
});
});

Related

I am trying to send array of images but I am unable to get data in server using nodejs

Here is my plunker link
https://plnkr.co/edit/0I0bbymoekwpyIXSOFJu?p=catalogue
I want to know how upload array of images.
For the single file, it's working, for multiple files I want to know what I need to write in node js.
My code
router.route('/events')
.post(upload.single('event_image'),function(req,res){
console.log('**Inside create events**');
console.log(":req.body",req.body);
console.log(":req.fileeeeeee",req.body);
var event = new Event();
event.name = req.body.name;
event.description = req.body.description;
event.location = req.body.location;
event.startdate = req.body.startdate;
event.enddate = req.body.enddate;
event.tagline = req.body.tagline;
event.password = req.body.password;
event.passcode = getEventPasscode();
event.uid = req.body.user_id;
})
Use upload.array('event_images', 20) (20 is maxCount) instead of upload.single('event_image')
EDIT:
Here is a code snippet that shows working route in node.js
router.post('/upload',
function(req, res) {
upload.array('event_images', 20),
function(req, res) {
_.each(req.files, file => {
console.log(file.path);
console.log(file.name);
});
res.json();
}
);

Mongoose.create creating document but none of my data

I'm learning to use the mean stack and trying to build a url shortener. I've got a module that takes the req.params.UserUrl checks and makes sure it's a valid url then creates a random number that I want to use as the short route. I can't seem to find a way to save the random number so that I can check their next url request against it. After a google search it seemed maybe the most effecient way would be to save an object in the database with the long_url and the short_url:randomNumber. My code doesn't throw any errors but when I check my heroku database it has a new entry but only has the _id and __v that mLabs generates itself. Can someone tell me where I'm going wrong.
Route File
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var URLShortener = require(process.cwd()+'/public/Modules/urlShortener.module.js');
var ShortURL = require('../models/shortUrl.js');
router.get('/', function(req, res) {
res.render('index', { title: 'FreeCodeCamp Projects' });
});
router.get('/urlShortener', function(req, res){
res.render('freecodecamp/urlShortener', { title: 'Url Shortener Site'});
});
router.get('/urlShortener/:userUrl', function(req, res){
if(URLShortener.checkValidUrl(req.params.userUrl))
{
var UserUrl = req.params.userUrl;
var randNbr = URLShortener.assignRanNbr();
ShortURL.create(URLShortener.createUrlObj(UserUrl, randNbr), function (err, smallUrl) {
if (err) return console.log(err);
else res.json(smallUrl);
});
}
else
{
res.send('Invalid url');
}
});
router.get('/:short', function(req, res){
if(randNbr == req.params.short)
{
res.redirect(userUrl);
}
else
{
res.send('Not the correct shortcut');
}
});
module.exports = router;
Url Schema
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var shortUrlSchema = new Schema({
long_id:String,
short_id:Number
}, {collection: 'shortUrl'});
module.exports = mongoose.model('shortUrl', shortUrlSchema);
urlShortener Module
'use strict'
module.exports.checkValidUrl = function(url){
var pattern = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/);
return pattern.test(url);
}
module.exports.assignRanNbr = function(){
var randNbr = Math.floor(Math.random() * (9999 - 1 + 1)) + 1;
return randNbr;
}
module.exports.createUrlObj = function(url, num){
var urlObj = {};
urlObj.original_url = url;
urlObj.short_url = 'https://rawlejuglal-me-rawlejuglal-1.c9users.io/freecodecamp/'+num;
return urlObj;
}
Your createUrlObj method is returning an object with the properties original_url and short_url, but your shortUrlSchema properties are long_id and short_id. The property names in your create method need to match your schema. The property value types must also match your schema types (currently short_url is a string and short_id is a number). I think what you really want is for your createUrlObj method to be
module.exports.createUrlObj = function(url, num){
var urlObj = {};
urlObj.long_url = url;
urlObj.short_id = num;
return urlObj;
}
and your schema to be
var shortUrlSchema = new mongoose.Schema({
long_url: String,
short_id: Number
}, {collection: 'shortUrl'});
Additionally, your '/:short' route should have a call to the database since the randNbr and userUrl variables are not defined in that route.
router.get('/:short', function(req, res){
ShortUrl.findOne({short_id: req.params.short}, function(err, shortUrl){
if(err) res.send('Invalid Url');
res.redirect(shortUrl.long_url)
})
});

NodeJS Mongoose Not Save Data

My system will create around 30 collection for every hour. My server get thousands request for one hour. I have big data and multiple collections. And i use MongoDB-NodeJS for saving data.
The modelControl function of pariteModel class at the paritemodel.js -as the below codes- i do check if this schema is created before. And i will create schema or use created schema.
First collections creating and saving data to MongoDB. But when create another collections it's not doing. For example:
EURJPY_20160107_16 collection is created but EURJPY_20160107_17 collection is not create. I have check mongoose.models at modelparite.js EURJPY_20160107_17 is created but instance created from EURJPY_20160107_17 Schema not saved to database.
My server files like this:
app.js file is my bootstrap file:
var http = require('http'),
dispatcher = require('httpdispatcher');
require('./mongo.js');
function handleRequest(request, response){
try {
dispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}
var server = http.createServer(handleRequest);
server.listen(3663, function(){
console.log('listening the port: ' + 3663);
});
This is mongo.js which i call in app.js. This file uses for save data to mongodb:
var dispatcher = require('httpdispatcher'),
url = require('url'),
moment = require('moment'),
md = moment().format("YYYYMMDD_HH"),
myModel = require('./modelparite.js');
dispatcher.onGet('/mongo', function(req, res){
var url_parts = url.parse(req.url, true);
// This is collection name. Output like this: USDTRY_20160107_16
var colName = url_parts.query.symbol + '_' + md;
var tarih = new Date();
var pariteModel = myModel.returnModel(colName);
var yeniParite = new pariteModel({
symbol: url_parts.query.symbol,
bid: url_parts.query.bid,
ask: url_parts.query.ask,
timeup: moment(tarih).format("YYYY-MM-DD HH:mm:ss")
});
yeniParite.save(function (err, data) {
if (err) console.log(err);
console.dir(data,true);
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end();
});
And this is my model modelparite.js file which i call in mongo.js. This file uses to create schema with Mongoose:
var mongoose = require('mongoose'),
helper = require('./helper.js');
require('mongoose-double')(mongoose);
mongoose.connect('mongodb://localhost:27017/forex');
var pariteModel = {
pariteSchema: "",
initSchema: function(){
var Schema = mongoose.Schema;
this.pariteSchema = new Schema({
symbol: String,
bid: mongoose.Schema.Types.Double,
ask: mongoose.Schema.Types.Double,
timeup: Date
});
},
modelControl: function(modelName){
if(mongoose.models[modelName]){
return true;
}
return false;
},
returnModel: function(modelName){
modelName = helper.whichParity(modelName);
//console.log(modelName);
if(this.modelControl(modelName)){
//console.log(mongoose.model(modelName));
return mongoose.model(modelName);
}else{
this.initSchema();
return mongoose.model(modelName, this.pariteSchema);
}
},
}
module.exports = pariteModel;

On which format send file to save it on gridfs?

Hy every one,
Please , i 'm study on a project using nodeJS, and i would like to know , in which format my node client must send the file to the server ( is it in base64 format or else ?).
my client is :
//client.js
$('#file').on('change', function(e){
encode64(this);
});
function encode64(input) {
if (input.files){
chap.emit('test', { "test" : input.files[0] });
var FR= new FileReader();
FR.readAsDataURL(input.files[0]);
FR.onload = function(e) {
chap.emit('test', { "test" : e.target.result } );
}
}
}
My server side is :
socket.on('test', function(e){
var gs = new gridStore(db, e.test,"w");
gs.writeFile(new Buffer(e.test,"base64"), function(err,calb){
if (!err)
console.log('bien passe');
else
console.log('erreur');
});
});
But this doesn't work , i get this error :
TypeError: Bad argument
at Object.fs.fstat (fs.js:667:11)
Any one could help me ?
Normally this is how you store into gridFs . I have used it to store files. hope it works.
fs = require('fs'),
var gfs = require('gridfs-stream');
var form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
var file = files.file[0];
var filename = file.originalFilename; //filename
var contentType = file.headers['content-type'];
console.log(files)
var tmpPath = file.path ;// temporary path
var writestream = gfs.createWriteStream({filename: fileName});
// open a stream to the temporary file created by Express...
fs.createReadStream(tmpPath)
// and pipe it to gfs
.pipe(writestream);
writestream.on('close', function (file) {
// do something with `file`
res.send(value);
});
})

How to create a file using user input in nodejs?

I have a text area, where the user type in their text. Once they click save the content in the text area is send to the server side. In the server side I want to use the content to create a file. I have a variable called "usercode" which holds the content of the text area. I create a file,
fs.wirteFile(name + "java", usercode, function(){})
Name the file name, given by user. This does create a file, however the only thing in the file is "[object Object]".
here is my client side I am using jade:
extends layout
block content
div(id="ineditortxt")
h1(name="headings") #{title}
a(href='/signout', class='text-center new-account') Sign Out
div(id="editor")
|public class #{title}{
| public static void main(String[] args) {
|
| }
|}
script(src="src/ace.js", type="text/javascript")
script(type="text/javascript").
//var myRequest = new XMLHttpRequest();
var editor=ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/java");
$(document).ready(function(){
$("#save").click(function(event){
var content = editor.getValue();
$.ajax({
url:'/getcode',
type:'POST',
data: content,
jsonpCallback: 'callback'
});
event.preventDefault();
return false;
});
});
form(name="Save", id = "save")
input(type="submit", value="Save")
div(id="result")
|
Here is the server side i didn't include all the code, just the one related to this question:
var express = require('express');
var router = express();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var param = require('express-params');
var Parse = require('parse').Parse;
var http = require('http');
var fs = require('fs');
router.post('/editor', function(req, res){
name = req.body.newname;
res.render('Editor', {title: "" + name});
});
router.post('/getcode', function(req, res){
var usercode = req.body;
fs.writeFile(name + ".java", usercode, function(err){
if(err){
console.log(err);
} else{
console.log("The file is saved!");
}
})
res.send({code: "" + usercode});
console.log(usercode);
});
return router;
}
You are actually writing the req.body object to the file which is a JSON object to access the post data in your request.
You need to access the post data by form field name inside that object so if you have a form field named "myField", it's data will be available in req.body.myField
If you want to just write the whole object to the file, you need to first stringify the JSON object using JSON.stringify(req.body)
JSON.stringify is going to escape the string which you can fix by unescaping it using unescape(string)
On client side the code should be:
$(document).ready(function(){
$("#save").click(function(event){
var content = editor.getValue();
console.log("This is content: " + content);
$.ajax({
url:'/getcode',
type:'POST',
data: {'code': content},
processData: 'false',
});
event.preventDefault();
return false;
});
});
on the server side the code should be:
router.post('/getcode', function(req, res){
var usercode = req.body.code;
newname = name+".java";

Resources