3

I want to convert image from file upload element to base64 string.

I found a solution here How can you encode a string to Base64 in JavaScript?

The @SunnyMilenov answer but I am not sure what to pass to function

 encode : function (input) {...}

2 Answers 2

4

UPDATED Answer for HTML5 and IE without HTML5

you need to use FileReader.readAsDataURL() instead see js fiddle example

function getImage() {

    var reader = new FileReader();
    var f = document.getElementById("file-select").files;

    reader.onloadend = function () {
        console.log(reader.result);
    }
    reader.readAsDataURL(f[0]);

}
<form id="file-form" method="POST">
    <input type="file" id="file-select" />
</form>
<button onclick="getImage()" id="upload-button">Convert</button>

For IE without HTML5 you need to use an activex object and make sure you allow activex to run scripts in your internet options

enter image description here

<html>

<head>

<script>

// from http://stackoverflow.com/questions/7370943/retrieving-binary-file-content-using-javascript-base64-encode-it-and-reverse-de
function base64Encode(str) {
    var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out = "", i = 0, len = str.length, c1, c2, c3;
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += CHARS.charAt(c1 >> 2);
        out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += CHARS.charAt(c3 & 0x3F);
    }
    return out;
}

function readFile(filePath){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    f = fso.GetFile(filePath);
    var textStream = f.OpenAsTextStream();
    var fileData = base64Encode(textStream.Read(f.size));
    textStream.close();

    return fileData;
}

function getImage() {
    var filePath = document.getElementById("file-select").value;
    var fileData = readFile(filePath);
    document.getElementById("output").value = fileData;
}


</script>


</head>
<body>


<form id="file-form" method="POST">
    <input type="file" id="file-select" />
</form>
<button onclick="getImage()" id="upload-button">Convert</button>

<br>

<textarea id="output" cols="100" rows="20"></textarea>

</body>
</html>
Sign up to request clarification or add additional context in comments.

2 Comments

I want it for IE 9 or earlier
see my updated response for solutions with html5 and ie with no html5
0
<!DOCTYPE html>
<html>
<style type="text/css">

</style>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
      canvas.height = img.height;
      canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback.call(this, dataURL);
          // Clean up
        canvas = null; 
    };
    img.src = url;
  }


  $('#img2b64').submit(function(event){
      var imageUrl = $(this).find('input[name=url]').val();
      console.log('imageUrl', imageUrl);
      convertImgToBase64(imageUrl, function(base64Img){
          $('.output')
              .find('textarea')
                  .val(base64Img)
                  .end()
              .find('a')
                  .attr('href', base64Img)
                  .text(base64Img)
                  .end()
              .find('img')
                  .attr('src', base64Img);
      });

      event.preventDefault();
  });
});
</script>
</head>
<body>
<h2>Input</h2>  
<form class="input-group" id="img2b64">
    <input 
        type="url" 
        name="url" 
        class="form-control"
        placeholder="Insert an IMAGE-URL" 
        value="http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png"  
        required>
    <span class="input-group-btn">
        <input 
            type="submit" 
            class="btn btn-default">
    </span>
</form>

<hr>

<h2>Output</h2>        
<div class="output">
    <textarea class="form-control"></textarea><br>
    <a></a><br><br>
    <img><br>
</div>
</body>

</body>
</html>

1 Comment

I do not need it for html5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.