Skip to content

Instantly share code, notes, and snippets.

@johnnyclem
Created November 11, 2012 07:50
Show Gist options
  • Save johnnyclem/4054112 to your computer and use it in GitHub Desktop.
Save johnnyclem/4054112 to your computer and use it in GitHub Desktop.
Store an image in redis
var fs = require('fs'),
querystring = require('querystring'),
redis = require('redis'),
r = redis.createClient(),
allowedTypes = {
'text/javascript': 'js',
'text/css': 'css',
'image/png': 'png',
'image/jpeg': 'jpg',
'image/gif': 'gif',
'text/plain': 'txt'
},
allowedExtensions = [],
contentTypes = {};
for (ct in allowedTypes) {
allowedExtensions[allowedExtensions.length] = allowedTypes[ct];
contentTypes[allowedTypes[ct]] = ct;
}
var validFile = new RegExp('^\/[a-z]+\/[0-9a-z\-]+\.('+allowedExtensions.join('|')+')$');
// Never let something run as root when it's not needed!
if (process.getuid() == 0) {
process.setgid('www-data');
process.setuid('www-data');
}
exports.actions = function(req, res, ss) {
return {
uploadImage: function(data) {
data = data.split(';base64,');
var type = data[0].substr(5); // strip the data:
if (!allowedTypes[type]) {
return;
}
// Decode the base64 data to binary.
data = new Buffer(data[1], 'base64').toString('binary');
// Get the number of files in the upload dir.
fs.readdir('./client/static/uploads', function(err, files) {
if(!err) {
// Create a new file with a number as name that is one higher then the current amount of files in the uploads directory.
var name = './client/static/uploads/'+files.length+'.'+allowedTypes[type];
var lastPath = files.length+'.'+allowedTypes[type];
fs.writeFile(name, data, 'binary', function(err) {
console.log(lastPath+' uploaded');
ss.publish.all('uploadImage', lastPath);
r.set( 'bezelRoom'+lastPath, data, function() {
var msg = 'The photo has been saved at: /'+lastPath;
console.log( msg );
r.get( 'bezelRoom'+lastPath, function( err, data ) {
if( !data ) {
res.writeHead( 404 );
res.write( "No such room" );
res.end();
return res(false);
} else {
console.log(data);
//in here we should send the bezelRoom name back in the return cb
return res(true);
}
})
})
})
}
})
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment