2013-02-23 61 views
1

我有一小段JavaScript,用於對文件輸入字段進行一些驗證。它在Chrome,Safari,Opera,Firefox中工作正常,但它在Internet Explorer 9和更低版本中不起作用...我使用的是Jquery 1.8.3,顯然自1.4.2以來.change屬性應該可以與IE 。我也試過$(「的FileInput」)。住(‘變’......

無法看到這是怎麼回事,歡迎任何建議!

jQuery(document).ready(function($){ 

    // Detect sh*tty IE 
    if ($.browser.msie && $.browser.version <= 9) { 

    // Bind to property change 
    $(".fileInput").bind('propertychange', function() { 

     fileChange(this); 
    }); 

    } else { 

    $(".fileInput").change(function() { 

     fileChange(this); 
    }); 
    } 

    function fileChange($item) { 

    // Get the filename 
    var $fileName = $($item).val(); 
    var $inputId = $($item).attr('id'); 
    var $fakeName = $($item).val().split('\\').pop(); 
    var $fileSize = (($item.files[0].size)/1024)/1024; 
    var $ext = $($item).val().split('.').pop().toLowerCase(); 
    var $acceptFiles = ['jpg', 'jpeg']; 

    if ($.inArray($ext, $acceptFiles) == -1) { 

     alert('For security, we can only accept jpeg images'); 

     // Reset the value of $item item 
     $($item).val(''); 

     return; 
    } 

    // Make sure the file size isn't bigger than 1mb 
    if ($fileSize >= 1.8) { 

     alert("The image you've chosen is too big. \n\nWe accept images up to 2mb in size"); 

     // Reset the value of $item item 
     $($item).val(''); 

     return; 
    } 

    // Check that the file 
    if ($fileName != '') { 

     $fileNotification = $('<li>', { id: 'file_'+$inputId, class: 'fileNotification', text: $fakeName}); 

     // Append it to the list 
     $('#filesList').append($fileNotification); 
    } 

    // Hide the file input 
    $($item).css({display : 'none'}); 

    // Show the next field 
    $($item).next().show();  

    }; 
}); 

回答

0

這無關IE的change事件也不jQuery的處理程序,而是老IE的缺乏HTML5的API

IE9和下面do not supportFile API因此:。

var $fileSize = (($item.files[0].size)/1024)/1024; 

輸入元素的files財產是undefined在舊的IE瀏覽器,你會得到一個錯誤,因爲你無法訪問屬性undefined。也就是說,您將無法使用File API輕鬆測試舊IE中的文件大小客戶端。

而且舊的IE也不支持XHR2,你甚至不能通過Ajax發送文件來檢查服務器端的大小。如果你想讓這個測試在舊IE中運行,你需要一些非常難看的解決方法 - 例如自動提交表單到一個隱藏的iframe做文件大小檢查服務器端,或使用Flash。

我相信你有服務器端驗證反正作爲JS一個可以很容易地規避,所以只是把客戶端檢查到一個漸進增強將是圍繞一個更簡單的方法:

if ($item.files) { //browser supports the HTML5 File API, do the client-side check 
    var $fileSize = (($item.files[0].size)/1024)/1024; 
    if ($fileSize >= 1.8) { 
     alert("The image you've chosen is too big. \n\nWe accept images up to 2mb in size"); 
     $($item).val(''); 
     return; 
    } 
} 

這意味着舊IE用戶仍然可以選擇大文件,但只要您驗證表單數據服務器端(這對於任何真實世界的Web應用程序都是必需的),那麼您只需顯示一個有意義的錯誤消息。


ps。您不需要.split('\\').pop()輸入值 - 即使文件輸入顯示用戶的完整路徑,瀏覽器也不會允許JS知道磁盤中文件的完整路徑,只有文件名(除非您篡改安全設置,請參閱related)。

ps2。您不需要做嗅探$.browser更少綁定propertychange處理程序,change事件將觸發IE的文件輸入同其它瀏覽器一樣。

+1

這工作,對待感謝,優秀的東西。是的,也有服務器端驗證,它最初只在服務器上進行驗證,但是我們添加了這個功能,以便在人們點擊「發送」按鈕之前使體驗更加直觀。再次感謝 – ThePHPUnicorn 2013-02-23 15:26:27