如何用HTML5的FileReader生成Data Url
直接上源码
<!DOCTYPE html <html xmlns="http://www.w3.org/1999/xhtml" > <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>HTML5的FileReader生成Data Url - 优客志</title> <meta name="keywords" content="优客志-Data Url,HTML5,FileReader"/> <meta name="description" content="如何用HTML5的FileReader生成Data Url"/> <script type="text/javascript"> function buildDataUrl(source) { var file = source.files[0]; if(window.FileReader) { var fr = new FileReader(); fr.onloadend = function(e) { document.getElementById("txtBase64").value = e.target.result; document.getElementById("imgView").src = e.target.result; }; fr.readAsDataURL(file); } } </script> </head> <body> <center> <h3>如何用HTML5的FileReader生成Data Url</h3> <p> <input type="file" value="" onchange="buildDataUrl(this)" style="border:1px solid #808080; width:300px;" /> </p> <textarea id="txtBase64" cols="98" rows="33"></textarea> <img id="imgView" src="" style="width:380px;max-height: 500px;" /> </center> </body> </html>
最终效果图: