使用 jQuery 从输入 [type='file'] 获取文件名

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

Get filename from input [type='file'] using jQuery

jquery

提问by dido

This is the uploaded form.

这是上传的表格。

<form class="alert alert-info">
    <div>
        <b id = "select_file" class="span3" style="font-weight: bold; cursor: pointer; ">Please select image</b>
        <input class="span3" type="file" name="image_file" id="image_file" style="display:none " />
        <input disabled="true" type="button" value="Upload image" class="btn" />
    </div>
</form>

I use the following script to open a window with files. I want to show a file name in <b id = 'select_file'>.

我使用以下脚本打开一个包含文件的窗口。我想在<b id = 'select_file'>.

How can I do this?

我怎样才能做到这一点?

$('#select_file').click(function(){
    var _this = $(this);
    $('#image_file').show().focus().click().hide();

    var filename = $('#image_file').val();
    _this.html(filename);

    $('.btn').attr('disabled', false);
});

回答by Greg W

Getting the file name is fairly easy. As matsko points out, you cannot get the full file path on the user's computer for security reasons.

获取文件名相当容易。正如 matsko 指出的那样,出于安全原因,您无法获得用户计算机上的完整文件路径。

var file = $('#image_file')[0].files[0]
if (file){
  console.log(file.name);
}

回答by Jai

You have to do this on the change event of the input type filethis way:

您必须在input type file这种方式的更改事件上执行此操作:

$('#select_file').click(function() {
    $('#image_file').show();
    $('.btn').prop('disabled', false);
    $('#image_file').change(function() {
        var filename = $('#image_file').val();
        $('#select_file').html(filename);
    });
});?

回答by Pascalius

There is no jQuery function for this. You have to access the DOMelement and check the files property.

没有用于此的 jQuery 函数。您必须访问DOM元素并检查 files 属性。

document.getElementById("image_file").files[0];

Or

或者

$('#image_file')[0].files[0]

回答by Michel

This was a very important issue for me in order for my site to be multilingual. So here is my conclusion tested in Firefox and Chrome.

这对我来说是一个非常重要的问题,以便我的网站能够使用多种语言。所以这是我在 Firefox 和 Chrome 中测试的结论。

jQuery trigger comes in handy.

jQuery 触发器就派上用场了。

So this hides the standard boring type=filelabels. You can place any label you want and format anyway. I customized a script from http://demo.smarttutorials.net/ajax1/. The script allows multiple file uploads with thumbnail preview and uses PHP and MySQL.

所以这隐藏了标准的无聊type=file标签。您可以放置​​任何您想要的标签并进行格式化。我从http://demo.smarttutorials.net/ajax1/定制了一个脚本。该脚本允许使用缩略图预览上传多个文件,并使用 PHP 和 MySQL。

<form enctype="multipart/form-data" name='imageform' role="form"    ="imageform" method="post" action="upload_ajax.php">
    <div class="form-group">
        <div id="select_file">Select a file</div>
        <input class='file' type="file" style="display: none " class="form-control" name="images_up" id="images_up" placeholder="Please choose your image">
        <div id="my_file"></div>
        <span class="help-block"></span>
    </div>
    <div id="loader" style="display: none;">
        Please wait image uploading to server....
    </div>
    <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>

$('#select_file').click(function() {
    $('#images_up').trigger('click');
    $('#images_up').change(function() {
        var filename = $('#images_up').val();
        if (filename.substring(3,11) == 'fakepath') {
            filename = filename.substring(12);
        } // Remove c:\fake at beginning from localhost chrome
        $('#my_file').html(filename);
   });
});

回答by jonathan klevin

Try this to Get filename from input [type='file'] using jQuery.

尝试使用 jQuery 从输入 [type='file'] 获取文件名。

<script type="text/javascript">
    $(document).ready(function(){
        $('input[type="file"]').change(function(e){
            var fileName = e.target.files[0].name;
            alert('The file "' + fileName +  '" has been selected.');
        });
    });
</script>

Taken from @ jQueryPot

取自@jQueryPot

回答by Nisharg Shah

Using Bootstrap

使用引导程序

Remove form-control-fileClass from input field to avoid unwanted horizontal scroll bar

从输入字段中删除表单控制文件类以避免不需要的水平滚动条

Try this!!

尝试这个!!

$('#upload').change(function() {
    var filename = $('#upload').val();
    if (filename.substring(3,11) == 'fakepath') {
        filename = filename.substring(12);
    } // For Remove fakepath
    $("label[for='file_name'] b").html(filename);
    $("label[for='file_default']").text('Selected File: ');
    if (filename == "") {
        $("label[for='file_default']").text('No File Choosen');
    }
});
.custom_file {
  margin: auto;
  opacity: 0;
  position: absolute;
  z-index: -1;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
   <label for="upload" class="btn btn-sm btn-primary">Upload Image</label>
    <input type="file" class="text-center form-control-file custom_file" id="upload" name="user_image">
    <label for="file_default">No File Choosen </label>
    <label for="file_name"><b></b></label>
</div>

回答by user7661816

$("#filetosend").prop('files')[0]

回答by Julien Mazars

You can access to the properties you want passing an argument to your callback function (like evt), and then accessing the files with it (evt.target.files[0].name) :

您可以访问想要将参数传递给回调函数的属性(如evt),然后使用它访问文件 ( evt.target.files[0].name):

$("document").ready(function(){
  $("main").append('<input type="file" name="photo" id="upload-photo"/>');
  $('#upload-photo').on('change',function(evt) {
    alert(evt.target.files[0].name);
  });
});

回答by Alan Dong

var file = $('#YOURID > input[type="file"]'); file.value; // filename will be,

var file = $('#YOURID > input[type="file"]'); file.value; // filename will be,

In Chrome, it will be something like C:\fakepath\FILE_NAMEor undefinedif no file was selected.

在 Chrome 中,它会类似于C:\fakepath\FILE_NAME或者undefined如果没有选择文件。

It is a limitation or intention that the browser does not reveal the file structure of the local machine.

浏览器不显示本地机器的文件结构是一种限制或意图。

回答by Konstantin Kolomiets

If selected more 1 file:

如果选择更多 1 个文件:

$("input[type="file"]").change(function() {
   var files = $("input[type="file"]").prop("files");
   var names = $.map(files, function(val) { return val.name; });
   $(".some_div").text(names);
});

fileswill be a FileListobject. namesis an array of strings (file names).

files将是一个FileList对象。names是一个字符串数组(文件名)。