JavaScript獲得當前檔案的路徑

來源:互聯網
上載者:User

在ASP.NET中,獲得檔案的實體路徑可以使用server.mapPath()方法得到,

而在JavaScript中則是沒有這個方法的,這裡給出JavaScript如何獲得檔案的路徑:

 

 

function serverMapPath(fileName){
var syspath = location.href; 
syspath = syspath.toLowerCase();      //把路徑名稱轉換成小寫
myPosition = syspath.lastIndexOf("/");  // 擷取檔案路徑中的最後一個"/"

syspath = syspath.substring(0,parseInt(myPosition)+1); // 使用substring函數 截取"/"之前的字串,就得到目前的目錄的路徑 

syspath = syspath.replace("file:///","");   //這裡要把file:///替換為空白,否則會報錯

syspath = syspath.replace(new RegExp("%20","gm")," ");   // 如果檔案名稱中含有空格,則要還原空格,替換所有的 %20 為 " "

syspath = syspath + fileName; 
return syspath.toString();
}

 

大家知道在JavaScript中有個 location.href ,但是這個屬性有時候獲得的檔案路徑不一定正確。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.