2012-08-10 36 views
1

我試圖從上傳輸入提醒文件名。使用jQuery與「拆分」報警輸入「文件」文件名

這裏是我的fiddle

它的工作原理,但有在 「C:Fakepath ......」 類似的東西。 我只想要文件名,沒有假路徑。我嘗試使用split函數,但我不確定它爲什麼不起作用。

HTML示例:

<html> 
    <head> 
     <title>Test Page</title> 
     <script src="http://code.jquery.com/jquery-latest.js"></script> 
    </head> 
    <body> 
     <input type="file" id="tester" /> 
    </body> 
</html> 

示例腳本:

$(function() { 
    var bogus; 
    var triple; 
    $('#tester').change(function() { 

     triple = $('#tester').val(); 
     bogus = triple.split(/[\s/]+/); 

     alert(bogus[bogus.length - 1]); 
    }); 
}); 

任何想法?

謝謝!

+0

你就不能'$( '#測試')VAL()代替( 「C:\\ \\ fakepath」, 「」)'? – 2012-08-10 15:43:45

回答

6

你可以只逃脫斜線:

bogus = triple.split("\\"); 

更新小提琴:http://jsfiddle.net/johnkoer/xwdct/3/

+0

完美。很簡單!謝謝。 (直到11分鐘才能給你「答覆」檢查 – larin555 2012-08-10 15:37:15

0

如果您的Web瀏覽器支持File API(目前,這是任何Web瀏覽器不是IE),你可以從輸入的FileList對象中獲取文件名。

$(function() { 
    $('#tester').change(function() { 
     var files = this.files; 
     if (files && files.length) { 
      alert(files[0].name); //use the file api 
     } 
     else { 
      alert($(this).val().replace("C:\\fakepath\\", "")); //this is for IE 
     } 
    }); 
});​ 

例子:http://jsfiddle.net/NTICompass/xwdct/6/

文檔:。https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications