Javascript “输入类型 file.files”选择器在 jQuery 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14772753/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:51:26  来源:igfitidea点击:

"Input type file.files" selector not working in jQuery

javascriptjquery

提问by Oto Shavadze

I'm trying to get information about the file being uploaded in an HTML input with the following code:

我正在尝试使用以下代码获取有关在 HTML 输入中上传的文件的信息:

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = $("#my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>

But it doesn't work, and the console returns: $("#my_file").files is undefined

但它不起作用,控制台返回: $("#my_file").files is undefined

回答by luiges90

$("#my_file")is a jQuery object, and a jQuery object does not have a property files...

$("#my_file")是一个 jQuery 对象,一个 jQuery 对象没有属性files...

To get the DOM element out of jQuery, do

要从 jQuery 中获取 DOM 元素,请执行

($("#my_file"))[0].files[0].size


As an extra note, if you have not selected any file, ($("#my_file"))[0].files[0]gives you undefinedand ($("#my_file"))[0].files[0].sizewill throw error.
You are recommended to add a check...

作为一个额外的注意,如果你没有选择任何文件,($("#my_file"))[0].files[0]会给你undefined并且($("#my_file"))[0].files[0].size会抛出错误。
建议您添加一个检查...

if (($("#my_file"))[0].files.length > 0) {
    file_size = ($("#my_file"))[0].files[0].size
} else {
    // no file chosen!
}

回答by undefined

jQuery object doesn't have filesproperty, you can use the old getElementByIdor jQuery getmethod for selecting the DOM Element object.

jQuery 对象没有files属性,您可以使用旧的getElementById或 jQueryget方法来选择 DOM 元素对象。

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = document.getElementById("my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>

回答by Ratilal Sundhesa

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = document.getElementById("my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>