在一个实际项目中,总是不可避免的需要向服务器上传文件。对于大多数的文件存储,我们一般是将文件的路径存入数据库,通过路径获得文件。这里有两种方法,一种是存在webcontent中,一种是存入主机的硬盘中。从长远的角度来看,我个人比较赞成存在主机硬盘中。这里不得不解决一个问题。咱们的jsp文件是在tomcat容器中,无法访问容器外的资源(移动端同理)。因此,我们需要设置虚拟路径。
设置虚拟路径有很多方法,这里我提供一种方法。
在tomcat中的conf/server.xml中<host></host>之间增加代码。
<Context path="/upload" docBase="/Users/xuxuxiao/Documents/upload/" reloadable="true">
</Context>
path指的是相对路径,docbase指的是绝对路径。可以这么理解。我们在使用时用/upload/xxx相当于/Users/xuxuxiao/Documents/upload/xxx
这样之后,需要重启服务器。如果报404,将项目重新加入tomcat即可。
在这里顺便贴上我存储文件的代码。
private String saveFile(HttpServletRequest req, MultipartFile multipartFile,String id) {
// TODO Auto-generated method stub
if (!multipartFile.isEmpty()) {
//文件上传到的位置
//String filepathString=req.getServletContext().getRealPath("/")+"upload/"+multipartFile.getOriginalFilename();
String filepathString="/Users/xuxuxiao/Documents/upload/"+id+"/"+multipartFile.getOriginalFilename();
File newfileFile=new File(filepathString);
if (!newfileFile.getParentFile().exists()) {
newfileFile.getParentFile().mkdirs();
}
try {
multipartFile.transferTo(newfileFile);
return "/upload/"+id+"/"+multipartFile.getOriginalFilename();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
return null;
}
ps:如果客户端要访问这个文件,则使用ip+端口+相对路径。这样就可以访问到这个文件。