Upload image with formidable in node.js failed - image

I want use formidable with express in node.js to achieve upload image function,
what I do is :
app.configure(function () {
app.use(express.static(__dirname + "/media"));
app.use(express.bodyParser());
})
app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
console.log("log in parse");
console.log("fields type is " + typeof fields);
console.log("files type is " + typeof files);
console.log(files.image);
if (err) return res.send('You found error');
});
})
with this code, the image could upload successully, but the form.parse function seems doesn't been invoked, cuz the log doesn't been invoked
Why?What's wrong with my code?

express 3 bodyParser() uses formidable internally.
So this should work:
view.jade
form#fileupload(enctype="multipart/form-data")
input(type="hidden",name="user[id]", value="1")
input(type="file",name="photo[file]")
app.js
app.post('/upload', function (req, res) {
var userId = req.body.user.id;
var photo = req.files.photo.file;
});

Related

data to image reactJS

I'm trying to retrieve a picture from my API, I'm sending the data like this :
router.post('/loadpicture', function(req, res, next) {
var imgPath = __dirname + "/no_photo.png";
// var imgPath = __dirname + "/photototo.jpg";
fs.access(imgPath, fs.F_OK, (error) => {
if (error) {
console.log(error);
}
else {
res.sendFile(imgPath, (err) => { if (err) next(err); });
}
});
})
And I'm trying to display the picture like this:
var url = "data:image/png;base64,"+this.props.picture;
return (
<div>
<h1>Change your profile pictures</h1>
<img src={url} alt={'hello'}/>
</div>
);
But here is the result:
I don't know what can I do.. I tried to remove newlines and other spaces
with url.replace(/\s+/g, '') but it's not working.
UPDATE: I just replaced with this and it works :
router.post('/loadpicture', function(req, res, next) {
var imgPath = __dirname + "/no_photo.png";
var img = fs.readFileSync(imgPath);
res.writeHead(200, {'Content-Type': 'image/png' });
res.end(img.toString('base64'));
})

how to access to filename in my requst block in multer

I Need Access to file name in my request body because i want store in my db but i dont know handle that , this is my code :
var storage = multer.diskStorage({
destination: function (req, file, callback) {
var name = 'public/images/' + Math.floor((Math.random() * 10675712320) + 1);
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
** Im want pass name variable**
callback(null, name);
}
});
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
***upload(req, res, function (data) {
I need access to file name here because i want store in my db***
console.log(data);
res.end("File is uploaded");
});
});
Im try this way but not working :
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
callback(name, name);
}
});
you can access to path from req.file.path like this :
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
upload(req, res, function (data) {
console.log(req.file.path);
res.end("File is uploaded");
});
});

Is my express post request is correct?

I'm trying to understand how Post Request works with express. I my case I would like to be able to update an web API call (is this the right term ?) with Google Analytics API. Most of the examples I found here or there are about handling post message or sign in operation.
Following this question here is what I have understand. On the front-end, using axios here is what I need to pass :
axios.post("http://localhost:3000/endpoints", my_parameters)
I can easily send this on the server side with react/redux. however on the server side, I'm kind of lost. I've got the following API call :
var key = require('./client_id.json')
var jwtClient = ...
var VIEW_ID = "ga:80820965";
var authorize = function( cb ) {
jwtClient.authorize(function(err) {
if (err) {
console.log(err);
return;
} else {
if ( typeof cb === "function") {
cb();
}
}
});
}
var queryData = function(req, res) {
authorize(function() {
analytics.data.ga.get({
'auth': jwtClient,
'ids': VIEW_ID,
'metrics': 'ga:uniquePageviews',
'dimensions': 'ga:pagePath',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:uniquePageviews',
'max-results': 10,
}, function (err, response) {
if (err) {
console.log(err);
return;
}
res.send(response);
});
});
}
module.exports = {
queryData
};
and my express server set-up :
const app = express();
app.use('/', express.static('public'));
app.use('/', express.static('src'));
var ga = require('./src/apicall/gadata');
app.listen(process.env.PORT || 3000);
app.set('views', './src/views');
app.set('view engine', 'ejs');
app.use('/gadata', ga.queryData);
so after I've dispatched my axios.post, how do I handle it in my server.babel.js file ?
I guess I need to use a structure like this :
router.get('/newUser', (req, res) => {
TestUser.save({
name: 'sawyer',
email: 'sawyer#test.com'
}).then((result) => {
console.log('Saved!')
res.send(result)
})
})
but I don't really know how I should refactor it to pass my parameters so I can actually update my google analytics api call ?
thanks.

Simple bluebird example with restify doesn't work

taking straight from this post:
This code never executes.
var Promise = require("bluebird");
Promise.promisifyAll(require("restify"));
var restify = require("restify");
var http = require('http');
const PORT=7070;
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
var server = http.createServer(handleRequest);
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
var client = restify.createJsonClientAsync({
url: 'http://127.0.0.1:7070'
});
client.get("/foo").spread(function(req, res, obj) {
console.log(obj);
});
I only put together this simple example to prove it to myself after my production code didn't work. I can hit localhost:7070 with curl and I get the expected results.
In a nutshell: I need to execute 3 GET calls to a server before I can create a POST and hence my need for promises.
Anyone can shed some insight? I can't imagine this being simpler.
UPDATE
Apparently i did not read the question correctly, here is a working example of 2 gets using a promisified restify json client. you would just do another spread in the body of the second spread for your post.
var promise = require('bluebird');
var restify = require('restify');
promise.promisifyAll(restify.JsonClient.prototype);
var client = restify.createJsonClient({
url: 'http://localhost:8080',
version: '*'
});
client.getAsync('/api/resource/1').spread(function(req, res, obj) {
console.log('result 1', obj);
return client.getAsync('/api/resource/2').spread(function(req, res, obj) {
console.log('result 2', obj);
});
});
As I stated in my comments, I would not promisify restify itself. Instead I would use either a handler whose body executes promise code or a chain of handlers (which can also have promises in the body). restify should only receive the request and execute the handler.
I will use modified versions of the basic example from the restify page to illustrate each.
Promise in the message body using knex.js which returns a promise
var knex = require('knex')(connectionConfig);
var restify = require('restify');
function promisePost(req, res, next) {
// get 1
knex.select('*')
.from('table1')
.where('id', '=', req.body.table1_id)
.then(function(result1) {
// get 2
return knex.select('*')
.from('table2')
.where('id', '=', req.body.table2_id)
.then(function(result2) {
return knex('table3').insert({
table1_value: result1.value,
table2_value: result2.value
})
.then(function(result3) {
res.send(result3);
return next();
});
});
});
}
var server = restify.createServer();
server.use(restify.bodyParser());
server.post('/myroute', promisePost);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
now with chained handlers
var knex = require('knex')(connectionConfig);
var restify = require('restify');
function get1(req, res, next) {
knex.select('*').from('table1')
.where('id', '=', req.body.table1_id)
.then(function(result1) {
res.locals.result1 = result1;
return next();
});
}
function get2(req, res, next) {
knex.select('*').from('table2')
.where('id', '=', req.body.table2_id)
.then(function(result2) {
res.locals.result2 = result2;
return next();
});
}
function post(req, res, next) {
knex('table3').insert({
table1_value: res.locals.result1,
table2_value: res.locals.result2
})
.then(function(result3) {
res.send(result3);
return next();
});
}
var server = restify.createServer();
server.use(restify.bodyParser());
server.post('/myroute', get1, get2, post);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});

Nodejs random query

I'm trying to get a random item from my local database using ajax.The first time i do a ajax request i get a random item afterwards every ajax request return the same item.
var express = require('express')
var app = express();
var customers = require('./module');
var pg = require('pg');
var conString = "postgres://postgres:pass#localhost/test";
var client = new pg.Client(conString);
app.get('/res', function(req, res) {
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT * FROM t_items OFFSET random()*300 LIMIT 1', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0]);
res.contentType('json');
res.send({ some: result.rows[0] });
client.end();
});
});
});
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.set('port', (process.env.PORT || 5000))
app.use(express.static(__dirname + '/public'))
app.get('/',function(req, res){
res.render("index");
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
})
If I try to wrap it in app.post('/req' )....
i get could not connect to postgres [Error: Connection terminated]
I've tried with client pooling but still the same problem
Just move your query inside function app.get('/res', function(req, res)
This happening because db query is executed only once. To prevent it - move your code inside /res route, and it will be executed every request.

Resources