Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
<input type="file" id="asd"/>

i would like to get the image in base64 once the user choosed that (before ssubmitting upload form)

So somenthing like :

$(input).on('change',function(){
 var data = $(this).val().base64file(); // it is not a plugin is just an example
 alert(data);
});

i red about File API and other stuffs, i would like a simple and cross-browsers solution (IE6/IE7 excluded obviously)

Any help appriciated thanks.

share|improve this question
And what did you not understand about the HTML5 File api? What did you try? What did not work? – epascarello Jul 17 at 21:03
@epascarello they are not fully supported actually caniuse.com/#feat=fileapi i need a work around, especially cause android versions are still used (old versions) as well as for old iOS versions, and i also would like to involve IE9 which is still used a lot :P – bombastic Jul 17 at 21:04
a workaround for what? What are you trying to do with the file? base64file() - is that a plugin? – David Jul 17 at 21:05
@David i just would like to get the base64 file once the user select the file from his pc, base64file() is just an example – bombastic Jul 17 at 21:06
Well If you need to support browsers that do not support it, you will have to find another technology that can read the files. For those browsers, you might be stuck uploading it. You can only do what the browser allows you to do. – epascarello Jul 17 at 21:11
show 6 more commentsadd comment (requires an account with 50 reputation)

1 Answer

up vote 1 down vote accepted

LIVE DEMO

(Working in FF, Chrome, Opera ...I'm sorry for all other browsers)

function readImage(input) {
    if ( input.files && input.files[0] ) {
        var FR= new FileReader();
        FR.onload = function(e) {
             $('#img').attr( "src", e.target.result );
             $('#base').text( e.target.result );
        };       
        FR.readAsDataURL( input.files[0] );
    }
}

$("#asd").change(function(){
    readImage( this );
});

HTML:

<input type='file' id="asd" />
<img id="img" src="" />
<div id="base"></div>

(P.S: The size of an base64 encoded image is ~25% bigger that the original size)

More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

share|improve this answer
yep thank you, so actually i can see File reader is no fully supported, how can i make the same supporting also old android/iOS devices ? – bombastic Jul 18 at 6:30
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.