0

How to decode the param values received which were received as Base64 encoded form and insert into database ?

This is what i have tried.

  • According to this i am getting one value recieved from the client as param value and inserting into server ( I have recieved the request at POST )
  • No base64 encoding is done here

I am using this code at present :

var express = require('express')
 , async = require('async')
 , http = require('http')
 , mysql = require('mysql');

var app = express();

var connection = mysql.createConnection({
   host: 'localhost',
   user: '******',
   password: "******",
   database: 'posting_information_DB'
});

connection.connect();

// all environments
app.set('port', process.env.PORT || 1234);

app.use(express.static(__dirname + '/public/images'));


app.post('/Name/',function(request,response,next){


app.use(express.bodyParser());

   var keyName=request.query.Key;
   var name_of_restaurants;
   async.series( [

       function(callback) {

          connection.query('INSERT INTO details (name) VALUES (?)', [keyName], function (err, rows, fields) 
              {
                      console.log('Connection result error ' + err);        
                      callback();
              });
       }

  // Send the response
] );
} );


http.createServer(app).listen(app.get('port'), function(){
 console.log('Express server listening on port ' + app.get('port'));
});

What i am trying to do !

  • Now what changes should i need to make so that when i need recieve a image and string as two param values
  • These values are Base64 encoded
  • How to decode these Base64 here and then insert the retrieved param values to database

How to modify my posted Express code !

Thanks !

user568109
  • 47,225
  • 17
  • 99
  • 123
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • 1
    You can decode base64 with a buffer object: `new Buffer(b64string, 'base64').toString('binary')` – Michael Tang Nov 25 '13 at 10:37
  • @ Michael Tang ..... Can you Edit the code with your solution as your answer ? ..... I am a newbie ! – Devrath Nov 25 '13 at 10:39
  • 2
    also, I think you're misusing caolan's async library. you might want to define a callback for the async.series call itself, so you can take an action after your query is done. check out the [documentation](https://github.com/caolan/async#series). however, since you only have one async function in series and you are already utilizing it's callback, you might not even need the async library (just stick your `res.send()` or such in the query callback). – Michael Tang Nov 25 '13 at 20:31

1 Answers1

1

You can retrieve the image parameter using request.params and then create a Buffer object, specify the base64 encoding and then convert it using the .toString() method.

app.post('/Name/', function(request, response, next){
  var image = new Buffer(request.params.image, 'base64').toString('binary');
  // do the database insert...
});
Paul Mougel
  • 16,728
  • 6
  • 57
  • 64