javascript - "Input type file.files"选择器在 jQuery 中不起作用

标签 javascript jquery

我正在尝试使用以下代码在 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>

但是不行,控制台返回:$("#my_file").files is undefined

最佳答案

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

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

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

作为额外说明,如果您没有选择任何文件,($("#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!
}

关于javascript - "Input type file.files"选择器在 jQuery 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14772753/

相关文章:

javascript - jQuery - 如何将文本值写入隐藏字段供以后使用?

javascript - 如何重置嵌套的 ng-repeat

javascript - Jquery 不从数字中删除逗号和美元符号

javascript - 谷歌地图 API V3 : Make the circle of the radius search markers clickable

javascript - 如何在 HTML 文件中编码图像数据?

javascript - 具有动态 div 的 CSS 垂直居中

javascript - Angular 2-RC4 动态内容加载

javascript - 如何使用字符串中的匹配项获取所有单词

jquery - 找出所有宽度大于xxx的元素输出到控制台

javascript - onclick 不触发所有观察者的 next()