jQuery:获取从<input type =“file”/>中select的文件名

这个代码应该在IE中工作(甚至不要在Firefox中testing它),但它不。 我想要的是显示附件的名称。 任何帮助?

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

这只是写作这么简单:

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

无论如何,我build议使用名称或ID属性来select你的input。 而事件,它应该是这样的:

 $('input[type=file]').change(function(e){ $in=$(this); $in.next().html($in.val()); }); 
 $('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\

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

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

其他一些有用的命令是:

获取文件的名称:

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

要获取文件的types:

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

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

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

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

你也不必on('change'使用这些命令,你可以随时获得这些值,例如你可以上传文件,当用户点击upload ,只需使用我列出的命令即可。

我曾使用以下哪些工作正常。

 $('#fileAttached').attr('value', $('#attachment').val()) 
 <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> 
 //get file input var $el = $('input[type=file]'); //set the next siblings (the span) text to the input value $el.next().text( $el.val() ); 

添加一个隐藏的重置button:

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

点击重置button清除input。

 $("#Reset1").click(); 
 <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>