servlet上传图片服务器路径问题

1.在servlet中上传图片,上传的文件夹是imge在webroot下,主要代码如下

private void saveImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
//保存的图片的名称
fileName =System.currentTimeMillis() + ".jpg";
//获得imge文件夹在tomcat中的决定路径,basePath的值是C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.20\webapps\flexTest\imge
String basePath = request.getSession().getServletContext().getRealPath("/imge/");
filePath = basePath;
System.out.println("保存图片的地址为:"+filePath);
realFilePath = filePath+"\\"+fileName;
// 获得一个图片文件流,我这里是从flex中传过来的
BufferedImage bufferedImage = ImageIO.read(request.getInputStream());
if (bufferedImage != null) {
//保存图片到指定的目录和文件中
ImageIO.write(bufferedImage, "jpeg", new File(filePath , fileName));
}
}


2.当要把上面上传图片通过servlet展示到游览器上时,取的路径如下:

private void printImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//获得服务器的地址,不能直接获取本机tomcat的绝对路径,不然游览器读取不了指定的图片文件
// basePath的值是http://localhost:8080/flexTest
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
String showFile = basePath+"/imge/"+this.fileName;
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(" <img src="+showFile+">");
out.print("</img>");
System.out.println("有显示图片的地址是"+showFile);
//showFile的值是 http://localhost:8080/flexTest//imge/1299470395060.jpg
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值