AbdulHamid AbdulHamid - 1 year ago 105
HTML Question

turn image binary data into img tag

When i do a post request to a route i have


i get something like: var file =

����JFIF��C��C��� ��

in the client i do:

var blob = new Blob([file], {type: 'image/png'});
var reader = new FileReader();

reader.onload = function (e) {
$('#result').attr('src', e.target.result);


but i get a corrupt image

what can i do?

if i do

img.src = 'data:image/png;base64,' + btoa(file);

i get:

Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Answer Source

At your backend you can do following:

var fs = require('fs');
fs.readFile(path to image from you file, 'base64', function(err, buf){
      /* Here you can send your base64 image data to client. Your base64 data is in buf. 
      I am using socket. You can just send. Read more about readFile function*/
      socket.emit('image upload', { image: true, buffer: buf });

As my client receives data from socket, I call a function:

socket.on('image upload', function(data){

var displayImage = function(data){
                var URL = 'data:image/jpg;base64,'+data.buffer;
                document.querySelector('#img-id').src = URL;

The image will then be showed in img tag. Hope this works for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download