2017-09-27 70 views
0
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(文件)時,它會返回我未定義的文件。等待文件讀取器返回true或false

+0

正確的,因爲你不是在'_validMimeType'返回任何東西 - 並搶先下一個問題,讀https://開頭stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –

+0

因爲這不是ajax調用。我需要它在onloadend函數結束時返回true或false。我該怎麼做 – Aatif

+0

你不能讓'_validMimeType'同步返回一個值,因爲它會異步確定返回值......你需要學習使用異步技術(回調,承諾等) - 你讀過https ://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call? –

回答

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 
}