文件上传之servlet3.0实现

来源:互联网 发布:百度地图编辑软件 编辑:程序博客网 时间:2024/06/05 09:57

文件上传之servlet3.0实现

标签(空格分隔): java fileupload


本例使用servlet3.0实现文件上传,项目管理使用maven

pom.xml配置

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.shushanfx</groupId>    <artifactId>servlet30</artifactId>    <version>1.0-SNAPSHOT</version>    <packaging>war</packaging>    <dependencies>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>javax.servlet-api</artifactId>            <version>3.1.0</version>            <scope>provided</scope>        </dependency>    </dependencies>    <build>        <finalName>servlet30</finalName>        <plugins>            <plugin>                <groupId>org.eclipse.jetty</groupId>                <artifactId>jetty-maven-plugin</artifactId>                <version>9.2.11.v20150529</version>                <configuration>                    <scanIntervalSeconds>10</scanIntervalSeconds>                    <webApp>                        <contextPath>/</contextPath>                    </webApp>                    <httpConnector>                        <port>8888</port>                    </httpConnector>                </configuration>            </plugin>        </plugins>    </build></project>

代码分析

  1. 导入servlet3.1的包,scope为provided,方便编译;
  2. 使用jetty作为启动服务,端口8888.

web.xml

web.xml内容基本上是没有用的

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    version="2.5"></web-app>

代码分析

注意此处的版本号使用的是2.5,如果使用2.4的话,jetty将无法识别Servlet3.0的注解

java代码

package com.shushanfx.servlet30;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.annotation.WebInitParam;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;import java.io.IOException;import java.io.PrintWriter;import java.util.Collection;import java.util.Iterator;import java.util.LinkedList;import java.util.List;/** * Created by dengjianxin on 2016/7/4. */@WebServlet(name = "uploadServlet", urlPatterns = "/upload.php",        loadOnStartup = 1, initParams = {        @WebInitParam(name = "name", value = "shushanfx提醒您<br />")})@MultipartConfig(        location = "upload",  //文件存放路径,指定的目录必须存在,否则会抛异常        maxFileSize = 8388608,  //最大上传文件大小,经测试应该是字节为单位        fileSizeThreshold = 819200, //当数据量大于该值时,内容将被写入文件。(specification中的解释的大概意思,不知道是不是指Buffer size),大小也是已字节单位        maxRequestSize = 8 * 1024 * 1024 * 6 //针对该 multipart/form-data 请求的最大数量,默认值为 -1,表示没有限制。以字节为单位。)public class UploadServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        req.setCharacterEncoding("UTF-8");        resp.setCharacterEncoding("UTF-8");        ServletConfig config = getServletConfig();        PrintWriter out = resp.getWriter();        out.println("<html>");        out.println("<body>");        out.println(config.getInitParameter("name"));        out.println("<form id=\"upload-form\" action=\"upload.php\" method=\"post\" enctype=\"multipart/form-data\">\n" +                "    <input type=\"file\" id=\"upload\" name=\"upload\" />\n" +                "    <input type=\"submit\" value=\"Upload\" />\n" +                "</form>");        if(req.getAttribute("fileNames")!=null){            out.println("fileNames -> ");            List<String> list = (List<String>) req.getAttribute("fileNames");            for(String item : list){                out.print(item + "&nbsp;");            }            out.println("<br />");        }        out.println("</body>");        out.println("</html>");    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        List<String> fileNames = new LinkedList<String>();        req.setCharacterEncoding("UTF-8");        Collection<Part> parts = req.getParts();        //遍历所有的表单内容,将表单中的文件写入上传文件目录        for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext();) {            Part part = iterator.next();            //从Part的content-disposition中提取上传文件的文件名            String fileName = part.getName();            if(fileName!=null){                fileNames.add(fileName + "|" + part.getSubmittedFileName() + "|" + part.getSize());                part.write(fileName);            }        }        req.setAttribute("fileNames", fileNames);        //显示上传的文件列表        doGet(req, resp);    }}

代码分析

  1. 使用Servlet3.0的注解功能,可以实现servlet/filter等自动注册;
  2. 使用MultipartConfig注解,系统在执行post之前解析body部分,分离文件和普通字段;
  3. 通过req.getParts()获取所有的上传列表;
  4. 遍历列表,每个文件代表一个Part对象。通过解析Part对象来实现对文件的读取。

运行

通过使用mvn clean jetty:run即可运行jetty服务,但是此种方式只能用作为开发调试,建议不要在生产环境中使用。
在浏览器访问http://localhost:8888/upload.php。

0 0
原创粉丝点击