2013-12-12 24 views
3

喜的Html5開發人員和開發人員HTML4太...如何獲得跨瀏覽器了兼容性對HTML5的window.fileReader API

我想知道是否有任何方式支持HTML5的window.fileReader API在IE8和以上。

下面的代碼:

if(window.fileReader){ 
    alert("supported"); // in html5 works and fires alert but not in IE8 
} 

其實,我想在提交前讀取文件的內容。

  • 我可以使用一些條件,如果window.fileReader支持則
    後續「A」使用HTML5的代碼行,否則如果不支持那麼
    使用一些其他的事情window.fileReader ...讀取文件
  • 我也想知道如何讀取文件內容而不使用
    HTML5 fileAPI ...但不使用ActiveXObject。

等待響應..

回答

7

還有多件,你將需要檢查的支持:

//Full File API support. 
if (window.FileReader && window.File && window.FileList && window.Blob) 
{ 
    //Supported 
} 

else alert("Not supported"); 

你的第二個要求:

我也想知道如何閱讀文件內容使用 HTML5 fileAPI ...但不使用ActiveXObject。

你可以做的是這樣的:

  1. 有一個iframe(你會被張貼到這一點)
  2. 有類型的輸入「文件」
  3. 當用戶選擇本地文件,可以使用JavaScript將其發佈到IFRAME(如document.getElementById("myForm").target = "myIframe"; document.getElementById("myForm").submit();
  4. iframe的發佈頁面(可能是PHP)讀取上傳的文件內容,並做了回調到父頁面(如<script>window.parent.someCallbackFunction(theFileCOntents);</script>
1

您可以隨時使用try-catch來檢查的FileReader()在瀏覽器的支持。

try { 
    var reader = new FileReader(); 
    //do something 
} 
catch(e) { 
    alert("Error: seems File API is not supported on your browser"); 
    //do something 
} 
2

您可以使用簡單的邏輯檢查功能,並在其中包含功能。

if ('FileReader' in window) { 
    // Do something with FileReader since it's supported 
} else { 
    // Do something with your polyfill solution 
} 

你可以嘗試這樣的一個解決方案,填充工具(在IE8的作品): https://github.com/Jahdrien/FileReader