javascript - getting base64 string from html file upload element -
i want convert image file upload element base64 string.
i found solution here how can encode string base64 in javascript?
the @sunnymilenov answer not sure pass function
encode : function (input) {...}
updated answer html5 , ie without html5
you need 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 need use activex object , make sure allow activex run scripts in internet options
<html> <head> <script> // 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 = "", = 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>
Comments
Post a Comment