在java中涉及到访问文件路径或是引用某个文件时,经常要用到获取当前项目上下文路径问题,有时上传图片或文件后需要下载文件,又涉及到文件的下载路径,于是将在java或jsp 里文件路径获取方法总结如下:
DATE:2010-07-15 hzg
String basePath = request.getContextPath();
basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+basePath+"/";
String servletPath = request.getServletPath();
String realPath=request.getRealPath("")+"\\";
//根据上传时间,生成不同的文件夹
String currFoder = m1.createFolder(realPath,uploadDate);
//文件保存目录路径
String savePath = realPath+currFoder;
//文件下载路径
String fileName = dto.getFileName("fileName");
String downLoadPath = basePath+currFoder+"/"+fileName;
//文件输出路径:
savePath========>>D:\Tomcat5.5\webapps\testProject\upload/2010-07-15/2010-07-15第1次.doc
downLoadPath===>>http://localhost:8081/testProject/upload/2010-07-15/2010-07-15第1次.doc
/**
* 创建存放上传文件的文件夹,如果不存在则自动创建
* @param realPath
* @param uploadDate
* @return
*/
public String createFolder(String realPath,String uploadDate){
String currFoder = "upload/"+uploadDate;
String fileFoder = realPath+currFoder;
FileOperate op = new FileOperate();
op.newFolder(fileFoder); //调用newFolder()方法创建文件夹
return currFoder;
}