Servlet-文件上传@MultipartConfig,Part

来源:互联网 发布:蔬菜交易软件 编辑:程序博客网 时间:2024/04/30 23:23

Servlet-文件上传@MultipartConfig,Part

sf2gis@163.com

2015年9月18日

 

1 目标:后台获取客户端上传文件内容并保存。

2 原理:前端使用文件标签将内容以二进制的形式传给容器。后端使用servlet的@MultipartConfig 标记servlet解析文件读取part。

3 流程:前端使用文件标签,后端读取part。

4 方法:前端上传文件,后端直接读取part。

参考:http://blog.csdn.net/xiazdong/article/details/7208316

4.1 前端上传文件:<inputtype=“file”>标签。

设置请求方式:method=”post”

设置编码类型:enctype=”multipart/form-data”

指定servlet:action=” /testAMap/ts"。

示例:

<formmethod="post" enctype="multipart/form-data"action="/testAMap/ts">

      <input type="file" name="file"/>

      <button type="submit"> submit</button>

</form>

4.2 后端读取文件:使用@MultipartConfig标记Servlet,读取part内容。

创建处理文件Servlet:使用@MultipartConfig标记。

处理part内容:读取文件名getSubmittedFileName(),文件大小getSize(),保存write()。

           Part part=request.getPart("file");

           pw.println("name="+part.getHeader("content-dispostion"));

           byte[] buff=new byte[(int) part.getSize()];

           part.getInputStream().read(buff);

5 示例

5.1 保存上传的文件到服务器指定目录

//后台文件处理Servlet:UploadFile.java

package lee;

 

import java.io.IOException;

importjavax.servlet.ServletException;

importjavax.servlet.annotation.MultipartConfig;

importjavax.servlet.annotation.WebServlet;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.Part;

 

/**

 * Servlet implementation class UploadFile

 */

@WebServlet("/UploadFile")

@MultipartConfig

public class UploadFileextends HttpServlet {

      private static final long serialVersionUID = 1L;

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public UploadFile() {

        super();

        // TODO Auto-generated constructor stub

    }

 

      /**

       * @seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

       */

      protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

           response.getWriter().append("Served at:").append(request.getContextPath());

           Part p=request.getPart("clientf");

           StringfileName=p.getSubmittedFileName();

           System.out.println("name="+fileName);

           System.out.println("size="+p.getSize());

           StringfilePath=getServletContext().getRealPath("/uploadfiles");

           System.out.println(filePath);

           p.write(filePath+"/"+fileName);

      }

 

      /**

       * @seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

       */

      protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

           doGet(request, response);

      }

 

}

//前台文件上传页面:a.jsp

<%@ pagelanguage="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"session="false"%>

<!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>Insert titlehere</title>

</head>

<body>

      this is a.jsp

      <%="aync return="+new java.util.Date() %>

      <%=request.getAttribute("async") %>

      <formmethod="post" enctype="multipart/form-data"action="UploadFile">

           <inputtype="file" name="clientf"/>

           <buttontype="submit"> submit</button>

      </form>

     

</body>

</html>

//结果

5.2 显示上传的文件内容

//upload.htm

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <title>Untitled</title>

</head>

 

<body>

 

Hello World!

<form method="post"enctype="multipart/form-data" action="/testAMap/ts">

      <inputtype="file" name="file"/>

      <buttontype="submit"> submit</button>

</form>

 

</body>

</html>

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appversion="3.0"

      xmlns="http://java.sun.com/xml/ns/javaee"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

                     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

    metadata-complete="false">

 

    <description>

      Servlet and JSP Examples.

    </description>

    <display-name>Servlet and JSPExamples</display-name>

</web-app>

//TestServlet.java

package com.thbd;

 

import java.io.IOException;

import java.io.PrintWriter;

 

importjavax.servlet.ServletException;

importjavax.servlet.annotation.MultipartConfig;

importjavax.servlet.annotation.WebServlet;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.Part;

 

/**

 * Servlet implementation class TestServlet

 */

@WebServlet(urlPatterns="/ts")

@MultipartConfig

public class TestServletextends HttpServlet {

      private static final long serialVersionUID = 1L;

 

    /**

     * Default constructor.

     */

    public TestServlet() {

        // TODO Auto-generated constructor stub

    }

 

      /**

       * @seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

       */

      protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

           response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

 

           Partpart=request.getPart("file");

           pw.println("name="+part.getHeader("content-dispostion"));

           byte[] buff=newbyte[(int) part.getSize()];

           part.getInputStream().read(buff);

           pw.println(part.getSize()+new String(buff));

      }

     

      /**

       * @seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

       */

      protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

           doGet(request,response);

      }

}

 

0 0