4

I have to convert an image to binary for storing it through IPFS and retrieve it again as a viewable image.

I should do this with javascript code. Does any body have any clear example of how to do this? Will Base64 help me?

Thanks in advance

we.are
  • 409
  • 2
  • 6
  • 15
  • Have you made some research before posting? I'm pretty sure you can find something. – sjahan Jul 26 '18 at 07:49
  • 1
    Possible duplicate of [How to convert image into base64 string using javascript](https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript) – sjahan Jul 26 '18 at 07:49

1 Answers1

10

Use File Reader:

/******************for base 64 *****************************/
function uploadFile(inputElement) {
  var file = inputElement.files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    console.log('Encoded Base 64 File String:', reader.result);
    
    /******************* for Binary ***********************/
    var data=(reader.result).split(',')[1];
     var binaryBlob = atob(data);
     console.log('Encoded Binary File String:', binaryBlob);
  }
  reader.readAsDataURL(file);
}
<input type="file" onchange="uploadFile(this)" />
Dinesh Ghule
  • 3,423
  • 4
  • 19
  • 39