2012-05-17 97 views
0

確定選擇的文件的類型在JavaScript在一個<input type="file" >元件,我選擇擴展.SRT的一個文件以及確定使用javascript.I的文件的類型嘗試這個在所有瀏覽器

var file=document.getElementById('fselect').files[0]; 
success = file.type =='application/x-subrip'? true : false; 
console.log('selected a file of type='+file.type); 
console.log('selected a subtitle file='+success); 

然而,我得到預期的結果只在chrome 18.0.1025.168

selected a file of type= application/x-subrip 
selected a subtitle file= true 

firefox 12與螢火安裝,我得到

selected a file of type= 
selected a subtitle file= false 

我很困惑這個..如何能一致地確定兩個瀏覽器中的文件類型?

回答

0

您可以使用HTML5的File API。它目前支持在每一個現代瀏覽器包括IE 9

http://www.html5rocks.com/en/tutorials/file/dndfiles/

function handleFileSelect(evt) { 
    var files = evt.target.files;     // file list 
    for (var i = 0, f; f = files[i]; i++) { 
     if(f.type){ 
      console.log(f.type); 
     }else{ 
      var match = f.name.match(/^.+(\.[^\.]+)$/); 
      if(match) { 
       console.log(match[1]); 
      }else{ 
       console.log('no MIME type nor extension'); 
      } 
     } 
    } 
} 

document 
    .getElementById('files') 
    .addEventListener('change', handleFileSelect, false); 

<input type="file" id="files"> 

現場演示:http://jsfiddle.net/DerekL/f2WmJ/

應該是在同樣的瀏覽器,因爲它是TANDARD。

+0

我懷疑問題是瀏覽器無法識別'srt'文件擴展名,因此不知道MIME類型,而不是JavaScript從瀏覽器中檢索MIME類型的失敗。 – icktoofay

+0

@icktoofay - 也許是這樣,但使用HTML5更好。 –

+0

問題中的代碼訪問'input'元素上的'files'屬性[[在HTML5中定義]](http://dev.w3.org/html5/spec/common-input-element-apis.html #DOM的輸入文件)。因此,問題中的代碼已經在使用HTML5。 – icktoofay

0
<input type="file" onChange="showExcelData(this)"> 

function showExcelData(event) 
{ 
    var file=event.value; 
    file=file.substr(file.lastIndexOf("/")+1,file.length); 
    file=file.substr(file.lastIndexOf(".")+1,file.length); 
    console.log(file); 

    /* You Can Return the Data or Anything You Want to Do */ 
}