Java Web 使用getPart()、getParts()上传文件

来源:互联网 发布:nginx 跳转 url不变 编辑:程序博客网 时间:2024/06/05 14:10

在Servlet3.0中新增了getPart()和getParts()函数用来处理上传文件,getPart()用于上传单文件,getParts()用于上传多个文件。

一、利用getPart()上传单个文件
新建一个web工程,创建一个UploadFile.java文件继承HttpServlet。

package com.uploadfile.part;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;@MultipartConfig(location = "D:/tmp/", maxFileSize = 1024 * 1024 * 10)public class UploadFile extends HttpServlet {    private static final long serialVersionUID = 1L;    public UploadFile() {        super();    }    public void destroy() {        super.destroy();    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        Part part = request.getPart("filename");        //获取文件名称        String filename = getFilename(part);        part.write(filename);        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<HTML>");        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");        out.println("  <BODY>");        out.print("<script>alert(\"上传文件成功\")</script>");        out.println("  </BODY>");        out.println("</HTML>");        out.flush();        out.close();    }    private String getFilename(Part part) {        if (part == null) {            return null;        }        String fileName = part.getHeader("content-disposition");        if (isBlank(fileName)) {            return null;        }        return substringBetween(fileName, "filename=\"", "\"");    }    public static boolean isBlank(String str) {        int strLen;        if (str == null || (strLen = str.length()) == 0)            return true;        for (int i = 0; i < strLen; i++) {            if (!Character.isWhitespace(str.charAt(i))) {                return false;            }        }        return true;    }    public static String substringBetween(String str, String open, String close) {        if (str == null || open == null || close == null)            return null;        int start = str.indexOf(open);        if (start != -1) {            int end = str.indexOf(close, start + open.length());            if (end != -1)                return str.substring(start + open.length(), end);        }        return null;    }    public void init() throws ServletException {    }}

location = “D:/tmp/” 表示上传的文件的存放地址,因此需要先在D盘新建一个tmp文件夹。maxFileSize = 1024 * 1024 * 10 表示上传文件大小的最大值,默认值为-1L,表示不限制大小。
再在WebRoot文件夹下新建一个File.jsp用来编写上传文件界面。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%    String path = request.getContextPath();    String basePath = request.getScheme() + "://"            + request.getServerName() + ":" + request.getServerPort()            + path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>上传文件</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"></head><body>    <form action="<%=request.getContextPath()%>/servlet/UploadFile"        method="post" enctype="multipart/form-data">        选择文件:<input type="file" name="filename" /> <input type="submit"            name="file_submit" value="提交">    </form></body></html>

运行Tomcat,在浏览器输入“http://localhost:8080/UploadFile/File.jsp”即可打开上传界面。UploadFile是工程名。

二、利用getParts()上传多个文件
创建一个UploadFiles.java文件继承HttpServlet

package com.uploadfile.part;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;@MultipartConfig(location = "D:/tmp/", maxFileSize = 1024 * 1024 * 10)public class UploadFiles extends HttpServlet {    private static final long serialVersionUID = 1L;    public UploadFiles() {        super();    }    public void destroy() {        super.destroy();    }    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        this.doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        for (Part part : request.getParts()) {            if (part != null && part.getName().startsWith("filename")) {                String filename = getFilename(part);                //因为上传框有多个,为了避免有的上传框没有选择文件导致出错,这里需要判断filename是否为null或为空                if (filename != null && !"".equals(filename))                    part.write(filename);            }        }        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<HTML>");        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");        out.println("  <BODY>");        out.print("<script>alert(\"上传文件成功\")</script>");        out.println("  </BODY>");        out.println("</HTML>");        out.flush();        out.close();    }    private String getFilename(Part part) {        if (part == null) {            return null;        }        String fileName = part.getHeader("content-disposition");        if (isBlank(fileName)) {            return null;        }        return substringBetween(fileName, "filename=\"", "\"");    }    public static boolean isBlank(String str) {        int strLen;        if (str == null || (strLen = str.length()) == 0)            return true;        for (int i = 0; i < strLen; i++) {            if (!Character.isWhitespace(str.charAt(i))) {                return false;            }        }        return true;    }    public static String substringBetween(String str, String open, String close) {        if (str == null || open == null || close == null)            return null;        int start = str.indexOf(open);        if (start != -1) {            int end = str.indexOf(close, start + open.length());            if (end != -1)                return str.substring(start + open.length(), end);        }        return null;    }    public void init() throws ServletException {    }}

再在WebRoot文件夹下新建一个Files.jsp用来编写上传文件界面。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%    String path = request.getContextPath();    String basePath = request.getScheme() + "://"            + request.getServerName() + ":" + request.getServerPort()            + path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>上传文件</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"></head><body>    <form action="<%=request.getContextPath()%>/servlet/UploadFiles" method="post" enctype="multipart/form-data">           选择文件一:<input type="file" name="filename1" />         <br>         选择文件二:<input type="file" name="filename2" />         <br>         选择文件三:<input type="file" name="filename3" />         <br>        <input type="submit" name="file_submit" value="提交">    </form></body></html>

然后再次访问Files.jsp页面,就可上传多个文件了

这里写图片描述

注意:在使用getPart()和getParts()方法时,必须用MultipartConfig注解,这样servlet才能获得Part对象。

0 0