0
点赞
收藏
分享

微信扫一扫

上传文件到虚拟路径下



java web项目有一个上传图片功能,使用的是xheditor插件中的图片上传功能。遇到一个问题:文件上传到服务器上是没问题的,但是重启服务器或者重新部署以后以前上传的图片都会丢失,原因是文件上传到服务器以后需要写到一个真实的磁盘路径下,所以需要有绝对路径,用这种方式获取:
String uploadPath = request.getSession().getServletContext().getRealPath("/uploadImg") ;
这样获取到的是tomcat的安装目录C:\Program Files (x86)\apache-tomcat-6.0.30\wtpwebapps\myProject\uploadImg。每次重启或部署就会覆盖掉tomcat下面的应用程序,肯定是不行的。
解决办法就是将图片上传到虚拟路径下:
在tomcat的server.xml文件中host之间添加 <Host> <Context docBase="D:/images" path="/img" /></Host> 然后就可以这样访问了localhost:8080/img/xxx
为了方便应用的迁移,在java代码中最好不要使用绝对路径,所以就用到了配置文件,在src目录下新建一个imgPath.properties文件配置两个键值:
imgPath=/img
imgRealPath=D:\\images
相关配置介绍完就直接上代码:

long fileName=System.currentTimeMillis();
//TODO 改为properties配置文件的方式获取绝对路径
ResourceBundle rb = ResourceBundle.getBundle("imgPath", Locale.getDefault());
String imgPath=rb.getString("imgPath");//相对路径
String imgRealPath=rb.getString("imgRealPath");//硬盘存放路径
System.out.println("realPath:"+imgPath+" realPath:"+imgRealPath);
File file = new File(imgRealPath);
if(!file.exists()){
file.mkdirs();
}
InputStream is=new FileInputStream(filedata);
File outFile = new File(imgRealPath+"/"+fileName+".jpg");// 输出文件
OutputStream os = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int len = 0;
while ((len=is.read(buffer))!=-1) {
os.write(buffer,0,len);
}
is.close();
os.close();
response.setCharacterEncoding("utf-8");
out=response.getWriter();
//TODO 应返回远程机地址
out.println("{'err':'','msg':'"+imgPath+"/"+fileName+".jpg'}");


以上为主要代码。


举报

相关推荐

0 条评论