jQuery:获取从 <input type="file" /> 中选择的文件名

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

jQuery: get the file name selected from <input type="file" />

jqueryeventscopyfile-io

提问by Thinker

This code should work in IE(don't even test it in Firefox), but it doesn't. What I want is to display the name of the attached file. Any help?

这段代码应该在 IE 中工作(甚至不要在 Firefox 中测试它),但它没有。我想要的是显示附件的名称。有什么帮助吗?

<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>

回答by Thinker

It is just such simple as writing:

就是这么简单的写:

$('input[type=file]').val()

Anyway, I suggest using name or ID attribute to select your input. And with event, it should look like this:

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

$('input[type=file]').change(function(e){
  $in=$(this);
  $in.next().html($in.val());
});

回答by Anatolii Pazhyn

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

This code will not show C:\fakepath\before file name in Google Chrome in case of using .val().

此代码将不会显示C:\fakepath\在使用的情况下,之前在谷歌浏览器的文件名.val()

回答by James111

The simplest way is to simply use the following line of jquery, using this you don't get the /fakepathnonsense, you straight up get the file that was uploaded:

最简单的方法是简单地使用以下行jquery,使用这个你不会得到/fakepath废话,你直接得到上传的文件:

$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id

Some other useful commands are:

其他一些有用的命令是:

To get the name of the file:

要获取文件名:

$('input[type=file]')[0].files[0].name; // This gets the file name

To get the type of the file:

要获取文件的类型:

If I were to upload a PNG, it would return image/png

如果我要上传 PNG,它会返回 image/png

$("#imgUpload")[0].files[0].type

To get the size (in bytes) of the file:

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

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

Also you don't have to use these commands on('change', you can get the values at any time, for instance you may have a file upload and when the user clicks upload, you simply use the commands I listed.

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

回答by Anil Gupta

<input onchange="readURL(this);"  type="file" name="userfile" />
<img src="" id="blah"/>
<script>
 function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah')
                    .attr('src', e.target.result)
                    .width(150).height(200);
        };

        reader.readAsDataURL(input.files[0]);
        //console.log(reader);
        //alert(reader.readAsDataURL(input.files[0]));
    }
}
</script>

回答by ihmar

I had used following which worked correctly.

我使用了以下工作正常的方法。

$('#fileAttached').attr('value', $('#attachment').val())

回答by redsquare

//get file input
var $el = $('input[type=file]');
//set the next siblings (the span) text to the input value 
$el.next().text( $el.val() );

回答by daniel ye

Add a hidden reset button :

添加隐藏的重置按钮:

<input id="Reset1" type="reset" value="reset" class="hidden" />

Click the reset button to clear the input.

单击重置按钮清除输入。

$("#Reset1").click();

回答by Raghuraj Singh Gurjar

<input onchange="readURL(this);"  type="file" name="userfile" />
<img src="" id="viewImage"/>
<script>
 function readURL(fileName) {
    if (fileName.files && fileName.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#viewImage')
                    .attr('src', e.target.result)
                    .width(150).height(200);
        };

        reader.readAsDataURL(fileName.files[0]);
    }
}
</script>