0

I want to convert image to base64 before sedig to server. how to do it in jquery?

html:

  <input id="imgFld" type="file" accept="image/*;capture=camera" style="display:block;"/>  

 <input type="submit" id="submitImage" name=submit/>

js:

$(document).ready(function(){

alert("hello");

$("#submitImage").on('click',function(e){
    e.preventDefault();

    var ext = $('#imgFld').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
        alert('Invalid extension!, Please choose the right extension - gif, jpg/jpeg or png');
    }
    else{

        //covert to base64 and send ajax post
    }
 });
Smitha
  • 6,110
  • 24
  • 90
  • 161
  • Classic question - Possible duplicate of http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript – Jeremy Thille May 29 '15 at 08:32

1 Answers1

0

You can simply print the uploaded image to an HTML5 <canvas> and then later you can use toDataURL() method of canvas element which will return A DOMString containing the requested data URI.

Read about toDataURL() method here

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

checkout this example which is doing <canvas> to bse64

http://jsfiddle.net/handtrix/yvq5y/

Akshay Khale
  • 8,151
  • 8
  • 50
  • 58