I'm using MEAN.io and i'm trying to upload a base64 encoded image.
Client side, AngularJS:
// Image we're going to send it out
var base64Image = files[i];
var file = {
image: base64Image,
type: type,
filetype: extension,
characterId: character._id
};
var newFile = new MediaSendBase64(file);
newFile.$save(function(image) {
if ( !image ) {
console.log('ERROR IMAGE');
}
else {
console.log('SUCCESS.');
console.log(image);
}
});
Server side, NodeJS, controller:
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
exports.uploadBase64 = function(req, res, next) {
var uploadPath = path.normalize(process.cwd() + '/packages/characters/public/assets/uploads/'),
data = new Buffer(''),
imgURL = undefined, // public URL to show the pic
type = undefined;
// In case the '/uploads' directoy doesn't exist
if( !fs.existsSync(uploadPath) ) {
fs.mkdirSync(uploadPath, 0755);
}
// Decoding the base64 image
var data = new Buffer(req.body.image, 'base64');
// Creating the name for the file --> characterId + type + timestamp + extension
var filename = req.body.characterId + '-' + req.body.type + '-' + new Date().getTime().toString() + '.' + req.body.filetype;
// Writing the image to filesystem
fs.writeFile(uploadPath + filename, data, function (err) {
if ( err ) {
console.log(err);
return res.status(500).json({
error: 'Cannot upload the image. Sorry.'
});
}
console.log('SAVED ON HD');
console.log('FINISHING');
// Sending success response
res.json({
imgURL: imgURL,
type: type
});
});
};
The thing is the file stored in /uploads isn't work. I can't see the image. The base64 image is sent and the file is written to hard disk, but it is not possible to open it.
What's wrong? Any suggestion?
Thanks!