Servlet实现上传下载

文件的上传下载在Web开发中会经常遇到,使用基本的I/O(输入/输出)流当然可以完成这项操作,但是出于对开发效率和程序运行效率方面的考虑,在实际开发过程中一般采用第三方的组件来完成这个上传功能。

本例选择使用commons-fileupload组件,使用的时候需要commons-io的支持。将commons-fileupload-1.2.2.jar与commons-io-2.1.jar复制到应用项目的WEB-INF/lib文件夹中。这时commons-fileupload组件的配置工作就完成了,可以在项目中开始使用commons-fileupload组件提供的文件上传功能。

1. 文件上传

1.1 上传页面

<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() +"://"
         + request.getServerName() +":" + request.getServerPort()
         + path + "/";
%>
 
<!DOCTYPE HTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <base href="<%=basePath%>">
 
      <title>My JSP 'index.jsp' startingpage</title>
      <meta http-equiv="pragma"content="no-cache">
      <meta http-equiv="cache-control"content="no-cache">
      <meta http-equiv="expires"content="0">
      <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">
      <meta http-equiv="description"content="This is my page">
      <!--
  <link rel="stylesheet"type="text/css" href="styles.css">
  -->
  </head>
 
  <body>
      上传文件示例
      <br />
      <form method="post"
         action="${pageContext.request.contextPath}/servlet/UploadServlet"
         enctype="multipart/form-data">
         文件:
         <input type="file"name="file">
         <input type="submit"value="上传" name="submit">
      </form>
  </body>
</html>

在这里需要注意的是,上传文件的时候表单中需要添加enctype=”multipart/form-data”的属性,而且最好使用POST方法提交表单。

1.2 Servlet代码

<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() +"://"
         + request.getServerName() +":" + request.getServerPort()
         + path + "/";
%>
 
<!DOCTYPE HTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <base href="<%=basePath%>">
 
      <title>My JSP 'index.jsp' startingpage</title>
      <meta http-equiv="pragma"content="no-cache">
      <meta http-equiv="cache-control"content="no-cache">
      <meta http-equiv="expires"content="0">
      <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">
      <meta http-equiv="description"content="This is my page">
      <!--
  <link rel="stylesheet"type="text/css" href="styles.css">
  -->
  </head>
 
  <body>
      上传文件示例
      <br />
      <form method="post"
         action="${pageContext.request.contextPath}/servlet/UploadServlet"
         enctype="multipart/form-data">
         文件:
         <input type="file"name="file">
         <input type="submit"value="上传" name="submit">
      </form>
  </body>
</html>

如果要上传多个文件,只需要在表单中添加文件选择输入框<input type=”File” name=”newFile”>即可,其中name属性可以任意命名。

2. 下载文件

用Servlet下载文件的时候,并不需要第三方组件的帮助,只需要对服务器的响应对象response进行简单地设置即可,下面的示例程序从当前应用项目的file目录下载一个名称为oracle.txt的文本文档。

importjava.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
 
importjavax.servlet.ServletException;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
 
public class DownloadServletextends HttpServlet {
 
  public void doGet(HttpServletRequest request,HttpServletResponse response)
         throws ServletException, IOException {
      doPost(request, response);
  }
 
  public void doPost(HttpServletRequest request,HttpServletResponse response)
         throws ServletException, IOException {
      String fileName ="file/oracle.txt";
      String filePath =this.getServletContext().getRealPath(fileName);
      
      /*
       * 对字符编码进行设置,用来支持中文的文件名
       */
      response.setCharacterEncoding("UTF-8");
      fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
      /*
       * 指明了这个Servlet的功能是输出文件,并且指明文件的位置
       */
      response.setHeader("Content-Disposition","attachment; filename="
             + fileName);
      /*
       * 指明了要输入文件的类型,其中image/bitmap就是BMP文件的MIME类型描述
       */
      response.setContentType("application/x-download");
 
      ServletOutputStream os =response.getOutputStream();
      BufferedOutputStream bos = newBufferedOutputStream(os);
 
      FileInputStream fis = newFileInputStream(new File(filePath));
      BufferedInputStream bis = newBufferedInputStream(fis);
      byte[] buff = new byte[1024];
      int length = 0;
      while ((length = bis.read(buff, 0,buff.length)) != -1) {
         bos.write(buff, 0, length);
      }
      bos.flush();
      bos.close();
      fis.close();
 
  }
}