读取器读取图像后返回结果转换为base 64

时间:2018-06-17 07:56:08

标签: javascript jquery base64 filereader

单击按钮后我对函数进行了测试,图像将转换为base64并返回结果,但它给我留空。为什么?

    $("#addNewProduct").click(function(){
        var uploadpImg1 = converttobase64(document.getElementById("uploadpImg1-input"));
        var uploadpImg2 = converttobase64(document.getElementById("uploadpImg2-input"));
        var uploadpImg3 = converttobase64(document.getElementById("uploadpImg3-input"));
        alert(uploadpImg1);
    });     
 function converttobase64(element) {
      var result ="";
      var file = element.files[0];

      var reader = new FileReader();

      reader.onloadend = function() {

        result = reader.result;       

      }

        reader.readAsDataURL(file);
        return result;
    }    

1 个答案:

答案 0 :(得分:0)

这是由于图像加载(asynchrone进程),使用callck back函数修复问题

由于asynchrone进程,你甚至会生成一个空字符串,即使是base64图像,

你可以做的是通过一个callback功能,你可以把你的下一代转发(​​你的警报)  ,并通过在回调函数

中将结果作为param传递,在onloadend上调用最后一个

见下面的摘录:



$("#addNewProduct").click(function() {
  var uploadpImg1 = converttobase64(document.getElementById("uploadpImg1-input"), function(result) {
    alert(result);
  });

});

function converttobase64(element, callback) {
  var result = "";
  var file = element.files[0];
  
  if (typeof(file) == 'undefined') return;

  var reader = new FileReader();

  reader.onloadend = function() {

    result = reader.result;
    callback(result);
  }

  reader.readAsDataURL(file);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="file" id="uploadpImg1-input" />

<button id="addNewProduct">add</button>
&#13;
&#13;
&#13;