上传文件时遇到的存放路径问题
public String uploadExcel(MultipartFile userExcel, FlowRecord flowrecord, HttpServletRequest request) throws IOException, InvalidFormatException {
// 获取附件的名称
String filename = userExcel.getOriginalFilename();
flowrecord.setFlre_filetitle(filename);
// 设置附件的保存地址目录
String dirPath = request.getServletContext().getRealPath("/attached/companyfiles/flow/import/" + flowrecord.getFlre_chan() + "/");
File filePath = new File(dirPath);
// 如果保存附件的地址不存在,就先创建目录
if ( !filePath.exists() ) {
filePath.mkdirs();
}
flowrecord.setFlre_filelink(dirPath);
try {
// 使用 MultipartFile 接口的方法完成附件上传到指定位置
userExcel.transferTo( new File( dirPath + filename ) );
} catch ( Exception e ) {
e.printStackTrace();
return "ATTACHEDFAIL";
}
return "OK";
}
使用以下方法获取的是在项目目录下的文件夹地址/文件路径:
String dirPath = request.getServletContext().getRealPath("/XXX/XXX/");
// 注明:/XXX/XXX/ 系各位在项目目录下的文件路径
比方说在Windows下,项目的目录是 F:\workspace\demo
而 /XXX/XXX/ 实际为 /attachedfiles/companyfiles/,即:
String dirPath = request.getServletContext().getRealPath("/attachedfiles/companyfiles/");
则附件会存放到此路径下面:F:\workspace\demo\attachedfiles\companyfiles
问题来了,如果我想把附件存放到 F:\workspace\ 这一级目录下的某个文件夹里,而不放在项目的目录文件夹里怎么办
于是我查了一会网上的资历,突然想到可以用最原始的修改替换路径字符串来达到目的。
具体改变如下:
……
String dirPath = request.getServletContext().getRealPath("");
dirPath = dirPath.replaceAll("demo", "attachedfile/companyfiles/");
……
其实是这样,request.getServletContext().getRealPath("")拿到的是项目的目录路径,即:
dirPath = "F:\workspace\demo";
那么,只需要将路径中从demo开始替换成其他路径,就可以实现开头提出大问题咯。。。所用的方法就是replace或者replaceAll。