a blog for those who code

Friday, 25 March 2016

How to Convert Uploaded Image to Base64 in Node.js

In this post we will be discussing about how to convert an uploaded image to base64 string in Node.js. In my previous posts we have discussed about File Upload in Node.js, where we have saved our image into the file system. Now lets say instead of saving into a file system you want your file data to be stored as base64 in the database.

So we will write a code where instead of saving into the file system we will convert the uploaded files into base64 for saving into the database. Just note that it is not advisable to save the image base64 into the database, as it is much more costlier than saving the image into file system.

Our Index.html will look like below where we have an input type file and submit to upload the files. Instead of normal upload you can also use Dropzone.js With Node.js.

<form enctype="multipart/form-data" action="/upload" method="post">
  <input type="file" name="photo" multiple />
  <input type="submit" value="Upload Image" name="submit" />
</form>

Our Server.js file will look like below where we will be using Multer which is a Node.js middleware for handling 'multipart/form-data'.  After uploading we will be looping through all the files using request.files (which has all the data related to uploaded files). One thing to note that we have to store the file to our file system temporarily and then we can delete the file using fs.unlink command. 

var express = require('express');
var multer = require('multer');
var fs = require('fs');
var app = express();
var port = 5000;

app.set('port', port); 

var storage = multer.diskStorage({
  destination: function (request, file, callback) {
    callback(null, '/example/uploads');
  },
  filename: function (request, file, callback) {
    console.log(file);
    callback(null, file.originalname)
  }
});

var upload = multer({storage: storage}).array('photo', 5);

app.get('/', function(resuest, response) {
  response.sendFile('/example/index.html');
});

app.post('/upload', function(request, response) {
  var filesBase64 = [];
  upload(request, response, function(err) {
    if(err) {
      console.log('Error Occured');
      return;
    }
    for(var i = 0; i < request.files.length; i++) {
      filesBase64.push({
fileName : request.files[i].originalname,
base64 : new Buffer(fs.readFileSync(request.files[i].path)).toString('base64')
      });
      fs.unlink(request.files[i].path);
      console.log('File Name : ' + filesBase64[i].fileName);

      console.log('Base 64 : ' + filesBase64[i].base64.substring(0,50));
    }
    response.end('Your Files Uploaded');
    console.log('Photo Uploaded');
  })
});

var server = app.listen(port, function () {
  console.log('Listening on port ' + server.address().port)
});

Now if you run the above code you will see that your filesBase64 array contains the data of the file which you can easily save in the database.


Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment