等待文件阅读器返回true或false

时间:2017-09-27 04:49:06

标签: javascript file upload mime reader

function _validMimeType(file) {
        var validSignatures = ['ffd8ffe0', '89504e47', '424d3804', '49492a00', 
        '4d4d002a' , 'd0cf11e0', '504b0304', '74686973', '7b5c7274', '25504446', 
        '52617221'];
        var slice = file.slice(0, 4);  
        var reader = new FileReader();    
        reader.onloadend = function(e) {
            var view = new DataView(reader.result),
            signature;
            if(view.byteLength == 8){
                signature = view.getUint32(0, false).toString(16) + 
                view.getUint32(4, false).toString(16);
            } else {
               signature = view.getUint32(0, false).toString(16);
            }
            for (var i = 0; i < validSignatures.length; i++) {
               if (signature == validSignatures[i].toLowerCase()) {
                   console.log(signature);
                   return  true;
               }
           }
           return false;
        }
        reader.readAsArrayBuffer(slice); 
    }

_validMimeType(file) returns me undefined

当我将文件从上传者传递到_validMimeType(文件)时,它返回undefined。

1 个答案:

答案 0 :(得分:0)

最简单的解决方案,因为FileReader是异步的,就是使用回调

function _validMimeType(file, callback) { // add callback argument
    var validSignatures = ['ffd8ffe0', '89504e47', '424d3804', '49492a00', 
    '4d4d002a' , 'd0cf11e0', '504b0304', '74686973', '7b5c7274', '25504446', 
    '52617221'];
    var slice = file.slice(0, 4);  
    var reader = new FileReader();    
    reader.onloadend = function(e) {
        var view = new DataView(reader.result),
        signature;
        if(view.byteLength == 8){
            signature = view.getUint32(0, false).toString(16) + 
            view.getUint32(4, false).toString(16);
        } else {
           signature = view.getUint32(0, false).toString(16);
        }
        for (var i = 0; i < validSignatures.length; i++) {
           if (signature == validSignatures[i].toLowerCase()) {
               console.log(signature);
               // change this
               return callback(true); // return so no fallthrough occurs
           }
       }
       // change this
       callback(false);
    }
    reader.readAsArrayBuffer(slice); 
}

_validMimeType(file, function(result) {
    // result is true or false
}