如何使用 JavaScript 访问文件元素的文件属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10102520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access files attribute of a file element using JavaScript
提问by Merianos Nikos
I have in my form an input element with type of file. What I like to do is to check the file size before the element is uploaded for validation issue. By using the majority of primary Web Browsers (except IE that always does things harder), I have find out that all are using an "attribute" that updated whenever I choose a new file and display the file size, as well other usefull information.
我的表单中有一个文件类型的输入元素。我喜欢做的是在上传元素以进行验证问题之前检查文件大小。通过使用大多数主要的 Web 浏览器(除了 IE 总是更难处理),我发现所有浏览器都在使用“属性”,每当我选择一个新文件并显示文件大小以及其他有用信息时,都会更新该属性。
Here is what I see in Chrome web browser :
这是我在 Chrome 网络浏览器中看到的内容:
The question now is, how can I access that value with JavaScript ? I have try several ways, but none was good for me ? Any good idea please ?
现在的问题是,如何使用 JavaScript 访问该值?我尝试了几种方法,但没有一种对我有好处?请问有什么好主意吗?
NOTE: In my web site I use jQuery, so is not important to be only regular JavaScript the answer.
注意:在我的网站中,我使用 jQuery,因此仅使用常规 JavaScript 作为答案并不重要。
Kind regards Merianos Nikos
亲切的问候 Merianos Nikos
采纳答案by JKing
//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]);
回答by molecule
or :
或者 :
$("#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);
});