使用jQuery从input获取文件名

这是上传的表格。

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

我使用下面的脚本来打开一个文件的窗口。 我想在<b id = 'select_file'>显示一个文件名。

我怎样才能做到这一点?

 $('#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); }); 

您必须这样对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); }); });​ 

获取文件名相当简单。 正如matsko所指出的那样,出于安全原因,您无法在用户计算机上获得完整的文件path。

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

这没有jQuery的function。 您必须访问DOM元素并检查文件属性。

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

要么

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

对于我来说,这是一个非常重要的问题,以使我的网站成为多种语言。 所以这里是我的结论在Firefox和Chrome中testing。

jQuery触发器派上用场。

所以这隐藏了标准的无聊type=file标签。 你可以放置任何你想要的标签和格式。 我从http://demo.smarttutorials.net/ajax1/定制了一个脚本。; 该脚本允许多个file upload与缩略图预览,并使用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); }); }); 

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

在Chrome中,它将类似于C:\fakepath\FILE_NAME ,如果没有select文件,则为undefined

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

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

您可以访问您想要传递参数到您的callback函数(如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); }); }); 

由于安全原因,这是不可能的。 至less不是现代浏览器。 这是因为任何访问文件path的代码都可能被认为是危险的,并且存在安全风险。 要么你会最终得到一个未定义的值,一个空string或错误将被抛出。

当提交文件表单时,浏览器将文件暂时caching到上传目录中,仅提交该文件的临时文件名和该文件的基本名称。