上传文件到虚拟路径下

  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'}" );

以上为主要代码。

转至:http://www.tuicool.com/articles/zea2ui

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值