获取使用javascript/Jquery的HTML5文件详细信息? [英] Get HTML5 file details with javascript/Jquery?

查看:76
本文介绍了获取使用javascript/Jquery的HTML5文件详细信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过html文件选择输入选择文件后,您应该如何访问文件的详细信息?

How are you supposed to access a file's details after the file has been selected through an html file select input?

我有这个html:

<input type="file" id="file-select" name="attachment"/>

使用一些jquery,当文件输入更改如下时,我可以查看文件的详细信息:

Using some jquery, I can view the file's details when the file input is changed like this:

$('#file-select').change(function(){
    var file = this.files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;
    console.log("File: " + file);
    console.log("Name: " + name);
    console.log("Size: " + size);
    console.log("Type: " + type);
});

是否有办法在更改"事件之外访问这些详细信息?例如,我认为这可以工作:

Is there a way to access these details outside the 'change' event? For example, I figured this would work:

$("#file-select").files[0].name

但是没有,并且给了我一个'Uncaught TypeError:无法读取未定义的属性'0''

but it doesn't, and gives me an 'Uncaught TypeError: Cannot read property '0' of undefined'

有什么想法我在做什么错吗?

Any ideas what I'm doing wrong?

推荐答案

,因为jQuery没有文件属性作为对象的一部分,因此不包含DOM元素.

because jQuery has no files property as part of the object, that is off the DOM element.

$("#file-select").get(0).files[0].name

$("#file-select")[0].files[0].name


基本示例显示如何通过单击按钮访问输入


Basic example showing how to access the input on a button click

$("button").on("click", function() {
  
    var ol = $("ol").empty();

    var files = $("#file-select").get(0).files; 
  
    for(var i=0; i<files.length;i++) {

        var file = files[i];
        var name = file.name;
        var size = file.size;
        var type = file.type;

        $("<li>" + name + " - " + size + " - " + type + "</li>").appendTo(ol);
      
      }
  
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="file" id="file-select" name="attachment"/>
<button>List</button>
<ol></ol>

这篇关于获取使用javascript/Jquery的HTML5文件详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆