【问题标题】:How to use a callback function with readAsDataURL()如何使用带有 readAsDataURL() 的回调函数
【发布时间】:2018-01-11 23:27:18
【问题描述】:

我已经阅读了这个https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced 和许多关于如何使用回调函数的示例,但是当我尝试复制我在示例中看到的内容时,我无法做到正确。

我正在尝试将 pdf 上传到输入,将上传的数据转换为二进制字符串,然后以某种方式使用该字符串。

问题是我无法让“使用字符串”部分等待“转换为二进制字符串”部分。

这是我的 jsfiddle,有一个问题的例子:

https://jsfiddle.net/97e01nmv/2/

<span>upload pdf here </span><input id="doc_upload" type = "file">

<br><br>

<button id="binary_string_btn">
Get Binary String
</button>

<br><br>

<button id="use_binary_string" style="display: none;">
Do something with the binary string
</button>

<script>

$("#binary_string_btn").click(function() {
  getBase64(document.getElementById("doc_upload").files[0], handleResult);
});

function getBase64(file, callback) {
   var reader = new FileReader();
   var binary_string = reader.readAsDataURL(file);
   callback(binary_string); 
};

function handleResult(binary_string) {
    console.log(binary_string);
    $("#use_binary_string").show();
};

</script>

这是我期望的工作方式:

1) 用户上传 pdf

2) 用户点击获取二进制字符串

3) convert 函数进行转换,完成后调用handleResult

4) handleResult 使用二进制字符串

实际发生的情况:

1) 用户上传 pdf

2) 用户点击获取二进制字符串

3) 转换完成前立即调用handleResult 函数

4) handleResult 尝试使用二进制字符串

【问题讨论】:

    标签: javascript jquery callback filereader


    【解决方案1】:

    Javascript 是异步的,所以你的回调会在文件被读取之前被触发。

    您需要在来自 FileReader 的事件中触发回调。查看文档以获取一个很好的示例 - https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload

    应该这样做 -

    function getBase64(file, callback) {
        var reader = new FileReader();
        reader.onload = function(event) {
            callback(event.target.result);
        };
        reader.readAsDataURL(file);
     } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      相关资源
      最近更新 更多