本文介绍如何在JavaScript中获取Web项目的绝对路径。通过解析window.document.location.href和location.pathname,分离主机地址与项目名称,拼接得到包含协议、域名、端口及项目名的完整路径,适用于文件上传下载等场景。
JS获取项目绝对路径的实现代码
在实际开发中,获取项目的绝对路径常用于处理文件的上传与下载操作。虽然JavaScript没有直接提供获取项目根路径的API,但可以通过解析当前页面的URL信息间接实现。具体实现逻辑如下所示:
核心代码实现
function getRealPath(){
//获取当前网址,如: http://localhost:8083/myproj/view/my.jsp
var curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: myproj/view/my.jsp
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8083
var localhostPaht=curWwwPath.substring(0,pos);
//获取带"/"的项目名,如:/myproj
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
//得到了 http://localhost:8083/myproj
var realPath=localhostPaht+projectName;
alert(realPath);
}