Js/Jquery获取input file的文件名

html代码:

     <input type= "file"  name= "file"  id= "file"  class= "input_text80" ></input>
 
js:
方法一:字符串截取
var  file = $( "#file" ).val();
var  fileName = getFileName(file);
  
function  getFileName(o){
     var  pos=o.lastIndexOf( "\\" );
     return  o.substring(pos+1);  
}
  
方法二:正则表达式
var  file = $( "#file" ).val();
var  strFileName=file.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi, "$1" );   //正则表达式获取文件名,不带后缀
var  FileExt=file.replace(/.+\./, "" );    //正则表达式获取后缀
 
 
 
//带文件后缀名

//获取文件名称   function getFileName(path) {       

var pos1 = path.lastIndexOf('/'); 

      var pos2 = path.lastIndexOf('\\');       

var pos = Math.max(pos1, pos2);      

 if (pos < 0) {           return path;       } 

      else {           return path.substring(pos + 1);       }   }    

  $(document).ready(function () {  

    $('#file').change(function () {        

   var str = $(this).val();         

  var fileName = getFileName(str);          

 var fileExt = str.substring(str.lastIndexOf('.') + 1);            

alert(fileName + "\r\n" + fileExt);      

 });  

});  

猜你喜欢

转载自www.cnblogs.com/qiao20/p/9015182.html