通過JS獲取文件上傳路徑

 最近在寫個小網站,用到了 fileupload 控件來上傳文件。因爲程序的某些需要,要獲取上傳文件的本地路徑,在 CS 代碼中使用的是 fileupload1.PostedFile.FileName ,結果發現得出來的只是文件名,不包含路徑,記得以前確實是用這樣的方法取得過路徑的。

      於是上網搜索了下,原來是因爲高版本的瀏覽器設定爲了安全起見,已經不會顯示文件路徑。只有想辦法用 JS 來獲取路徑了,測試了一下後發現。單獨只是使用 document.getElementById("fileupload1").value ,在 IE6 裏可以獲取全路徑,在 IE7,IE8 及火狐裏都是隻能獲得文件名。

      後來在網上找到了解決辦法, IE7,IE8 可以用如下代碼獲取文件路徑

程序代碼 程序代碼

 

    // 判斷瀏覽器類型

    var isIE = (document.all) ? true : false;

    var isIE7 = isIE && (navigator.userAgent.indexOf('MSIE 7.0') != -1);

    var isIE8 = isIE && (navigator.userAgent.indexOf('MSIE 8.0') != -1);

 

    var file=document.getElementById("fileupload1");

    if(isIE7 || isIE8)

    {

        file.select();

        var path=document.selection.createRange().text;

        document.selection.empty();

    }

 

       但是在火狐下還是沒辦法獲取文件路徑,看到網上有人說用 getAsDataURL() 方法可以獲取路徑。我測試了一下,用這個方法確實是可以獲得路徑,但是些路徑是被加密過的。於是繼續尋找其他方法。。。

      火狐下獲取上傳文件路徑的方法,需要先修改設置。在地址欄輸入 about:config ,然後修改 signed.applets.codebase_principal_support 的鍵值,將值修改爲 true 。然後再使用如下代碼,就可以獲得文件路徑。

 

程序代碼 程序代碼

try {

        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

    }

    catch (e) {

        alert(' 請更改瀏覽器設置 ');

        return;

    }

 

    var fname = document.getElementById("fileupload1").value;

    var file = Components.classes["@mozilla.org/file/local;1"]

        .createInstance(Components.interfaces.nsILocalFile);

    try {

        // Back slashes for windows

        file.initWithPath( fname.replace(////g, "//// ") );

    }

    catch(e) {

        if (e.result!=Components.results.NS_ERROR_FILE_UNRECOGNIZED_PATH) throw e;

        alert(' 無法加載文件 ');

        return;

    }

 

    alert(file.path);  // 取得文件路徑

 

 

    運行以上代碼時,瀏覽器會彈出警告,選擇”是“之後,即可獲得路徑。


本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/komodo_d/archive/2009/11/12/4802816.aspx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章