JavaWeb将图片显示在浏览器中
2015-05-29 17:04
627 查看
原文地址:点击打开链接
一、背景
用户上传了一张图片,图片到服务器后用户得到一个链接,可以将图片显示在浏览器上。
二、实现
假设项目名叫TestProject,文件放在项目根目录下的uploadImages文件夹下。
①图片名为英文,可直接通过链接打开图片
<a href="http://localhost:8080/TestProject/uploadImages/myImage.jpg">预览图片</a>
②图片名含有中文,通过Servlet将图片输出到浏览器上,使用图片在服务器上的绝对路径
showImage.jsp
<a href="/TestProject/showImageServlet?filename=测试的图片一枚.jpg">预览图片</a>
showImageServlet
public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception
{
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
String fname = request.getParameter("filename");
String newpath = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
String absolutePath = rootPath + newpath;
FileInputStream fis = new FileInputStream(absolutePath);
OutputStream os = response.getOutputStream();
try
{
int count = 0;
byte[] buffer = new byte[1024 * 1024];
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}
一、背景
用户上传了一张图片,图片到服务器后用户得到一个链接,可以将图片显示在浏览器上。
二、实现
假设项目名叫TestProject,文件放在项目根目录下的uploadImages文件夹下。
①图片名为英文,可直接通过链接打开图片
<a href="http://localhost:8080/TestProject/uploadImages/myImage.jpg">预览图片</a>
②图片名含有中文,通过Servlet将图片输出到浏览器上,使用图片在服务器上的绝对路径
showImage.jsp
<a href="/TestProject/showImageServlet?filename=测试的图片一枚.jpg">预览图片</a>
showImageServlet
public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception
{
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
String fname = request.getParameter("filename");
String newpath = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
String absolutePath = rootPath + newpath;
FileInputStream fis = new FileInputStream(absolutePath);
OutputStream os = response.getOutputStream();
try
{
int count = 0;
byte[] buffer = new byte[1024 * 1024];
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}
相关文章推荐
- SpringMVC入门学习(三)+Spring应用(整合)
- java cxf webservice 生成客户端 调用 服务端
- java 基础学习-03 api 中String类的学习
- Java 与中文字体
- 《Java程序设计》第一次作业:源代码计算器 目标二
- Eclipse快捷键
- JAVA基础五——面向对象一
- java文件下载
- RSA密钥,JAVA与.NET之间转换
- java开发中的23种设计模式(转)
- eclipse插件OpenExplorer快速打开文件目录
- JAVA -- 线程run和start的区别
- JAVA -- 线程run和start的区别
- JAVA -- 线程run和start的区别
- 课程实验一:目标一:输出该目录下指定类型文件(.cs, .java)的个数、文件的总行数、空行数、注释行数、代码行数
- 初学WEB项目,第一个增删改查的Demo,框架=SpringMVC
- Java安全之公钥与私钥
- java8 之默认方法
- Spring事务
- java中多线程笔记(一)