<input type="file" id="asd"/>

我想在用户 Select 后(提交表单之前)获得base64的图像

比如:

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

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

谢谢你的帮助.

推荐答案

function readFile() {
  
  if (this.files && this.files[0]) {
    
    var FR= new FileReader();
    
    FR.addEventListener("load", function(e) {
      document.getElementById("img").src       = e.target.result;
      document.getElementById("b64").innerHTML = e.target.result;
    }); 
    
    FR.readAsDataURL( this.files[0] );
  }
  
}

document.getElementById("inp").addEventListener("change", readFile);
<input id="inp" type='file'>
<p id="b64"></p>
<img id="img" height="150">

(P.S: A base64 encoded image (String) 4/3 the size of the original image data)

Check this answer for multiple images upload.

浏览器支持:http://caniuse.com/#search=file%20api

Jquery相关问答推荐

如何用each替换元素的attr href

为什么函数没有进入

如何在jQuery中判断粘贴剪贴板中字母输入的增加/减少

如何在 jQuery 中 Select 特定的表单元素?

如何滚动到AngularJS中的页面顶部?

使用 JavaScript/jQuery 重定向到 ASP.NET MVC 中的另一个页面

在 contenteditable div 中的插入符号处插入 html

JQuery手风琴自动高度问题

jQuery绑定到粘贴事件,如何获取粘贴的内容

如何在不导致页面滚动的情况下删除位置哈希?

用 jQuery 模拟按键

将 CSS 应用于 jQuery 对话框按钮

如果 iframe src 无法加载,则捕获错误.错误:-拒绝在框架中显示 'http://www.google.co.in/'..

获取跨域 iframe 的 DOM 内容

JQuery Ajax Post 导致 500 内部服务器错误

如何使用 Twitter Bootstrap 自动关闭alert

如何删除/更改 JQuery UI 自动完成助手文本?

Backbone.js - 事件,知道点击了什么

使用javascript将HTML页面中的div下载为pdf

jQuery向左滑动并显示