Thursday, 12 December 2013

Base64 string to image in Node Js (express).

FileReader dataurl   to write  image in Node Js (express).
 create data url and pass in ajax

      $.ajax({
                        type:'POST',
                        url:"/uploadimg",
                        data:{src:data}, // document.getElementById("small").src    base64 string
                        success: function (response) {
                              alert("hi");
                        },
                        error:function() {
                              alert('error');
                        }
       });


create post method in express


app.post('/uploadimg', SetJsonHeader, function (req, res) {
       console.log("call :   "+ req.body.src);

       var fs = require('fs');
       var data_url = req.body.src;

//  DataURL is prepended by meta data. You first need to remove that part before you create a base64  buffer.

       var matches = data_url.match(/^data:.+\/(.+);base64,(.*)$/);
       var ext = matches[1];
       var base64_data = matches[2];
       var buffer = new Buffer(base64_data, 'base64');
       fs.writeFile(__dirname +'/uploads', buffer, function (err) {
         res.send('success');
       });
             
            res.send({ ReturnVal:req.body.src });
    });

No comments:

Post a Comment