首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >文件:获取从<input type=“jQuery”/>中选择的文件名

文件:获取从<input type=“jQuery”/>中选择的文件名
EN

Stack Overflow用户
提问于 2009-08-19 10:39:58
回答 8查看 202.7K关注 0票数 92

这段代码应该可以在IE中运行(甚至不要在火狐中测试它),但它不能。我想要的是显示附加文件的名称。有什么帮助吗?

代码语言:javascript
复制
<html>
<head>
  <title>example</title>    
  <script type="text/javascript" src="../js/jquery.js"></script>
  <script type="text/javascript">  
        $(document).ready( function(){            
      $("#attach").after("<input id='fakeAttach' type='button' value='attach a file' />");      
      $("#fakeAttach").click(function() {            
        $("#attach").click();        
        $("#maxSize").after("<div id='temporary'><span id='attachedFile'></span><input id='remove' type='button' value='remove' /></div>");        
        $('#attach').change(function(){
          $("#fakeAttach").attr("disabled","disabled");          
          $("#attachedFile").html($(this).val());
        });        
        $("#remove").click(function(e){
          e.preventDefault();
          $("#attach").replaceWith($("#attach").clone());
          $("#fakeAttach").attr("disabled","");
          $("#temporary").remove();
        });
      })
    }); 
  </script> 
</head>
<body>
  <input id="attach" type="file" /><span id="maxSize">(less than 1MB)</span>    
</body>
</html>
EN

回答 8

Stack Overflow用户

发布于 2009-08-19 10:44:08

它就像写这样的简单:

代码语言:javascript
复制
$('input[type=file]').val()

无论如何,我建议使用name或ID属性来选择您的输入。对于事件,它应该看起来像这样:

代码语言:javascript
复制
$('input[type=file]').change(function(e){
  $in=$(this);
  $in.next().html($in.val());
});
票数 148
EN

Stack Overflow用户

发布于 2015-11-26 09:59:04

最简单的方法是简单地使用下面这行jquery,使用它你不会得到/fakepath的胡言乱语,而是直接得到上传的文件:

代码语言:javascript
复制
$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id

其他一些有用的命令包括:

要获取文件名,请执行以下操作:

代码语言:javascript
复制
$('input[type=file]')[0].files[0].name; // This gets the file name

要获取文件类型,请执行以下操作:

如果我上传一个PNG,它将返回image/png

代码语言:javascript
复制
$("#imgUpload")[0].files[0].type

要获取文件的大小(以字节为单位):

代码语言:javascript
复制
$("#imgUpload")[0].files[0].size

此外,您也不必使用这些命令on('change',您可以在任何时候获取这些值,例如,您可能有一个文件上传,当用户单击upload时,您只需使用我列出的命令。

票数 20
EN

Stack Overflow用户

发布于 2014-02-13 02:44:01

代码语言:javascript
复制
$('input[type=file]').change(function(e){
    $(this).parents('.parent-selector').find('.element-to-paste-filename').text(e.target.files[0].name);
});

在使用.val()的情况下,此代码不会在Google Chrome中的文件名前显示C:\fakepath\

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1299052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档