2012-04-11 116 views
5

我在我的表單中有一個文件類型的輸入元素。我喜歡做的是在元素上傳之前檢查文件大小是否存在驗證問題。通過使用大多數的主要Web瀏覽器(IE除外,總是讓事情變得更加困難),我發現所有使用的「屬性」都會在我選擇一個新文件並顯示文件大小以及其他有用信息時進行更新。如何使用JavaScript訪問文件元素的文件屬性

以下是我在Chrome網絡瀏覽器中看到:

enter image description here

現在的問題是,我怎麼能訪問該值使用JavaScript?我嘗試了幾種方法,但沒有一個對我有好處?有什麼好主意嗎?

注意:在我的網站中,我使用jQuery,因此,只有普通的JavaScript纔是重要的答案。

親切的問候 Merianos尼科斯

+4

可能DUP http://stackoverflow.com/questions/1440723/find-file-size-with-jquery – elclanrs 2012-04-11 08:39:40

回答

3
//use any ol' selector to get the <input /> element: 
var inputElement = document.querySelector("input[type='file']"); 

//then it's just like you'd access any object's attributes: 
var fileSize = inputElement.files[0].size; 
//note that it's a list of files, so you can loop through them 
//in case the element accepts multiple files 

//if you want all of the attributes, do something like: 
for (var key in inputElement.files[0]) 
    if (inputElement.files[0].hasOwnProperty(key)) 
     console.log(key,inputElement.files[0][key]); 
+0

是它也有可能以類似的方式獲取作者,PDF文件的創建者等屬性? – toothie 2015-08-22 03:19:57

0

或:

$("#btStartUpload").on("click", function(evt) {   

    var filesSelected = document.getElementById('btInput').files; // FileList object 
    // var filesSelected = $('#btInput')[0].files; // with jQuery, any jQuery object have it's DOM element accessed using [0] 
    // var filesSelected = $('input[type=file]')[0].files; 
    console.log(filesSelected); 
}); 
相關問題