NodeJS & Express: upload image file and refresh ALL linked screen (3)
Blogs20122012-06-04
NodeJS & Express: upload image file and refresh ALL linked screen (1)
This is my an other application o NodeJS - Use NodeJS and Express web framework to implement a very cool effect:
- in the webpage, there is a file upload form; user can upload image files from here.
- when submit, the image is uploaded to server directory, and reflect to current webpage without page refresh.
- meanwhile, all the web users could immediately see this uploaded image without refresh.
- exact the same as Facebookās ālikeā feature.
It is different from previous example, which doesnāt use upload form, instead, it uses a simple form input field. The forms are different, so the implement are quite different also. The following is the core app.js:
var my_dir = __dirname+'/public/';
var express = require('express'),
routes = require('./routes');
var app = module.exports = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
//app.get('/', routes.index); first time load ~/public/index.html
var html = require('fs').readFileSync(__dirname+'/public/index.html');
res.end(html);
});
app.post('/api/photos', function(req, res) {
console.log(JSON.stringify(req.files));
var serverPath = '/images/' + req.files.userPhoto.name;
require('fs').rename(
req.files.userPhoto.path,
my_dir + serverPath,
function(error) {
if(error) {
res.send({
error: 'Ah crap! Something bad happened'
});
return;
}
res.send({
path: serverPath
});
});
});
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode",
app.address().port, app.settings.env);
});
var nowjs = require("now");
var everyone = nowjs.initialize(app);
everyone.now.distributeMessage = function(message){
everyone.now.receiveMessage(message);
};
It is not perfect, but it works fine. The core part is the callback for app.post -> ā/api/photosā. In the following blog, I will list brief client-side code.