大部分情况,会从HttpServletResponse取得PrintWriter实例,使用println()对浏览器进行字符输出。然而有时候,需要直接对浏览器进行字节输出,这时可以使用HttpServletResponse的getOutputStream()方法取得ServletOutputStream实例,它是OutputStream的子类。
如图,我们希望让浏览器直接输入PDF文件。
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 输出二进制字符
* @author Barudisshu
*/
@WebServlet(name = "Download", urlPatterns = {"/download.do"})
public class Download extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String password = request.getParameter("password");
if ("123456".equals(password)) {
//设置MIME(Multipurpose Internet Mail Extensions)类型
response.setContentType("application/pdf");
//获取输入流对象
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/jdbc.pdf");
//获取输出流对象
OutputStream out = response.getOutputStream();
//读取PDF并输出至浏览器
writeBytes(in, out);
}
}
private void writeBytes(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
上传文件,并显示在客户端。
代码清单1:upload.xhtml (上传表单)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>上传文件</title>
<style type="text/css">
.container{
margin: 0 auto;
width: 400px;
border:thin solid #84d44f;
padding: 100px;
}
</style>
</head>
<body>
<div class="container">
<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><label for="file">上传文件:</label></td>
<td><input type="file" id="file" name="picture" value=""/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
代码清单2:UploadServlet.java (获取请求,并输入到服务器目录)
/**
* Function 负责文件的上传,并返回结果
* @author Barudisshu
*/
@MultipartConfig
@WebServlet(name = "UploadServlet", urlPatterns = {"/upload.do"})
public class UploadServlet extends HttpServlet {
private String contextPath;
@Override
public void init() throws ServletException {
contextPath = getServletContext().getRealPath("/");
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Part part = request.getPart("picture");
String fileName = getFileName(part);
writeTo(fileName, part);
//forward到显示
request.setAttribute("fileName", fileName);
request.getRequestDispatcher("show.jsp").forward(request, response);
}
//取得上传文件名
private String getFileName(Part part) {
String header = part.getHeader("Content-Disposition");
String fileName = header.substring(header.indexOf("filename=\"") + 10,
header.lastIndexOf("\""));
return fileName;
}
//存储文件
private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException {
InputStream in = part.getInputStream();
OutputStream out = new FileOutputStream(contextPath + fileName);
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
这里有很多限制,这使用的是Servlet 3.0 新的特征标注(Annotaion)类描述部署,一些低版本的服务器需要使用标准依赖部署描述文件(web.xml)来部署,另外Part也是Java EE 6.0新增的类,Part是一个接口继承于javax.servlet.http,代表一部分表单项目接收来自multipart/form-data的POST的请求。
代码清单3:show.jsp (显示类)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>图片显示</h1>
<a href="${fileName}">${fileName}</a>
</body>
</html>
这里使用EL表达式描述,优化了代码。
下面给出效果链接……
http://phantom.duapp.com/upload.xhtml