日期:2014-05-16  浏览次数:20355 次

JSP 显示服务器上的文件/图片
1 显示服务器上的图片
<?xml version="1.0" encoding="UTF-8" ?>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="org.apache.commons.io.IOUtils"%>
<%@page import="java.io.InputStream"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>读取服务器上的文件</title>
</head>
<body>
<%
	InputStream in = getServletContext().getResourceAsStream(
			"/upload/111.jpg");
	BufferedImage bfi = ImageIO.read(in);
	response.reset();//清除buffer
	response.setContentType("image/gif");
	ImageIO.write(bfi, "jpg", response.getOutputStream());
	out.clear();
	out = pageContext.pushBody();
%>
</body>
</html>


2 显示服务器上的文件
<?xml version="1.0" encoding="UTF-8" ?>
<%@page import="org.apache.commons.io.IOUtils"%>
<%@page import="java.io.InputStream"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>读取上传文件</title>
</head>
<body>
<%
	InputStream in = getServletContext().getResourceAsStream(
			"/upload/HIBERNATE.txt");
	out.println(IOUtils.toString(in));
%>
</body>
</html>



但是如果服务器上的文件内的字符不是UTF-8编码的 那么显示出去是会有乱码的
但是可以用GBK编码然后显示