图片转Base64

2022-01-21 00:00:00 input file base64 jquery javascript
<input type="file" id="asd"/>

一旦用户选择(在提交表单之前),我想在 base64 中获取图像

I would like to get the image in base64 once the user chose that (before submitting the form)

类似:

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

我阅读了有关 File API 和其他内容的信息,我想要一个简单的跨浏览器解决方案(IE6/IE7 显然不包括在内)

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:base64 编码的图像(字符串)是原始图像数据大小的 4/3)

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

检查这个答案多张图片上传.

浏览器支持:http://caniuse.com/#search=file%20api
更多信息:https://developer.mozilla.org/en-US/docs/Web/API/FileReader

相关文章