FileReader和Callbacks

时间:2015-05-18 21:12:37

标签: javascript

我正在努力重新尝试找到here的想法/代码(基本前提是通过简单地查看数据的前几个字节来计算文件类型)。

我完全按照自己的意愿行事 - 请参阅JSFIDDLE

继承我的代码:

function readTheFiles(file){

            var fileReader = new FileReader();
            fileReader.onloadend = function(e) {
            var fileHeader = new Uint8Array(e.target.result).subarray(0, 4);
            var header = "";
            for (var q = 0; q < fileHeader.length; q++) {
            header += fileHeader[q].toString(16);
            }
            alert(header);
            return header;              
            };
fileReader.readAsArrayBuffer(file);

} 


$("#input-id").on('change', function(event) {
        var files = event.target.files;
        var i = 0;
        for (var i = 0, file; file = files[i]; i++) {

         var headString = readTheFiles(file);
       alert(headString);

        }       
    });   

从我读过的内容(example 1example 2)我确信问题在于在 readTheFiles 函数中调用回调 - 可能是代码正在调用警报文件加载前的(headString)行(因此 readTheFiles 函数中的警报为什么会给出预期结果)。

我非常希望了解校长,而不仅仅是获得解决方案,因此我们将非常感激地收到任何指示/建议/协助。

非常感谢

1 个答案:

答案 0 :(得分:1)

我正在回答您关于为什么alert(headstring)来电告诉您“未定义”的问题。可能有更好的方法来发现您正在处理的文件类型。

您正在使用异步进程。我已经修改并评论了您的代码,以便您可以查看正在发生的顺序。您会看到我在与treat函数相同的范围内创建了on("change", ...)函数。然后我将此函数作为参数传递给readTheFiles()函数,以便稍后在读入文件时可以回调它。

function readTheFiles(file, callback, index){

    var fileReader = new FileReader();

    // 3. This function will be called when readAsArrayBuffer() has
    // finished reading the file 
    fileReader.onloadend = function(e) {
        var fileHeader = new Uint8Array(e.target.result).subarray(0, 4);
        var header = "";
        for (var q = 0; q < fileHeader.length; q++) {
            header += fileHeader[q].toString(16);
        }

        callback(header, index);
    };

    // 2. This gets called almost as soon as fileReader has been created
  fileReader.readAsArrayBuffer(file);
} 


$("#input-id").on('change', function(event) {
    var files = event.target.files;
    var i = 0;
    for (var i = 0, file; file = files[i]; i++) {
      // 1. This is executed for each file that you selected, immediately
      //    after selection. The treat() function is sent as a callback.
      //    It will be called later, when the file has been read in.
      //    Passing `i` as an argument allows you to see which order the
      //    files are treated in.
    var headString = readTheFiles(file, treat, i);
    }

    // 4. This is called by the callback(header) command inside the
    //    readTheFiles() function. The `treat` function was sent to
    //    readTheFiles as the `callback` argument. Putting brackets()
    //    after the function name executes it. Any value put inside
    //    the brackets is sent as an argument to this function.
    function treat(header, index) {
      alert("Header for file " + index + ":" + header);
    }
});