Servlet实现上传下载

Servlet实现上传下载

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

本例选择使用commons-fileupload组件,使用的时候需要commons-io的支持。将commons-fileupload-1.2.2.jarcommons-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();

 

  }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Servlet文件上传功能可以通过使用注解@MultipartConfig将Servlet标识为支持文件上传,然后将multipart/form-data的POST请求封装成Part对象,通过Part对象对上传的文件进行操作。以下是一个文件上传的Servlet示例代码: ```java @WebServlet("/uploadServlet") @MultipartConfig // 如果是文件上传,必须要设置该注解! public class UploadServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("文件上传..."); // 设置请求的编码格式 req.setCharacterEncoding("UTF-8"); // 获取普通表单项(获取参数) String uname = req.getParameter("uname"); // 表单中表单元素的name属性值 System.out.println("uname: " + uname); // 获取Part对象(Servlet将multipart/form-data的POST请求封装成Part对象) Part part = req.getPart("myfile"); // 通过Part对象得到上传的文件名 String fileName = part.getSubmittedFileName(); System.out.println("上传文件名:" + fileName); // 得到文件存放的路径 String filePath = req.getServletContext().getRealPath("/"); System.out.println("文件存放路径:" + filePath); // 上传文件到指定目录 part.write(filePath + "/" + fileName); } } ``` 而文件下载功能可以通过设置download属性来实现。以下是一个文件下载的JSP页面的示例代码: ```html <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件下载</title> </head> <body> <!-- 浏览器能够识别的资源 --> <a href="download/hello.txt">文本文件</a> <a href="download/pic.jpg">图片文件</a> <!-- 浏览器不能够识别的资源 --> <a href="download/zzz.rar">压缩文件</a> <hr> <a href="download/hello.txt" download>文本文件</a> <a href="download/pic.jpg" download="test.png">图片文件</a> <hr> <form action="downloadServlet"> 文件名:<input type="text" name="fileName" placeholder="请输入要下载的文件名"> <button>下载</button> </form> </body> </html> ``` 以上是文件上传和下载的实现方法,你可以根据需要进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值