1. 通过getInputStream()取得上传文件。

001 /**
002  * To change this template, choose Tools | Templates
003  * and open the template in the editor.
004  */
005 package net.individuals.web.servlet;
006   
007 import java.io.DataInputStream;
008 import java.io.FileOutputStream;
009 import java.io.IOException;
010 import javax.servlet.ServletException;
011 import javax.servlet.annotation.WebServlet;
012 import javax.servlet.http.HttpServlet;
013 import javax.servlet.http.HttpServletRequest;
014 import javax.servlet.http.HttpServletResponse;
015   
016 /**
017  *
018  * @author Barudisshu
019  */
020 @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
021 public class UploadServlet extends HttpServlet {
022   
023     /**
024      * Processes requests for both HTTP
025      * <code>GET</code> and
026      * <code>POST</code> methods.
027      *
028      * @param request servlet request
029      * @param response servlet response
030      * @throws ServletException if a servlet-specific error occurs
031      * @throws IOException if an I/O error occurs
032      */
033     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
034             throws ServletException, IOException {
035         response.setContentType("text/html;charset=UTF-8");
036         //读取请求Body
037         byte[] body = readBody(request);
038         //取得所有Body内容的字符串表示
039         String textBody = new String(body, "ISO-8859-1");
040         //取得上传的文件名称
041         String fileName = getFileName(textBody);
042         //取得文件开始与结束位置
043         Position p = getFilePosition(request, textBody);
044         //输出至文件
045         writeTo(fileName, body, p);
046     }
047   
048     //构造类
049     class Position {
050   
051         int begin;
052         int end;
053   
054         public Position(int begin, int end) {
055             this.begin = begin;
056             this.end = end;
057         }
058     }
059   
060     private byte[] readBody(HttpServletRequest request) throws IOException {
061         //获取请求文本字节长度
062         int formDataLength = request.getContentLength();
063         //取得ServletInputStream输入流对象
064         DataInputStream dataStream = new DataInputStream(request.getInputStream());
065         byte body[] = new byte[formDataLength];
066         int totalBytes = 0;
067         while (totalBytes < formDataLength) {
068             int bytes = dataStream.read(body, totalBytes, formDataLength);
069             totalBytes += bytes;
070         }
071         return body;
072     }
073   
074     private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
075         //取得文件区段边界信息
076         String contentType = request.getContentType();
077         String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
078         //取得实际上传文件的气势与结束位置
079         int pos = textBody.indexOf("filename=\"");
080         pos = textBody.indexOf("\n", pos) + 1;
081         pos = textBody.indexOf("\n", pos) + 1;
082         pos = textBody.indexOf("\n", pos) + 1;
083         int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
084         int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
085         int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;
086   
087         return new Position(begin, end);
088     }
089   
090     private String getFileName(String requestBody) {
091         String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);
092         fileName = fileName.substring(0, fileName.indexOf("\n"));
093         fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\""));
094   
095         return fileName;
096     }
097   
098     private void writeTo(String fileName, byte[] body, Position p) throws IOException {
099         FileOutputStream fileOutputStream = new FileOutputStream("e:/workspace/" + fileName);
100         fileOutputStream.write(body, p.begin, (p.end - p.begin));
101         fileOutputStream.flush();
102         fileOutputStream.close();
103     }
104   
105     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
106     /**
107      * Handles the HTTP
108      * <code>GET</code> method.
109      *
110      * @param request servlet request
111      * @param response servlet response
112      * @throws ServletException if a servlet-specific error occurs
113      * @throws IOException if an I/O error occurs
114      */
115     @Override
116     protected void doGet(HttpServletRequest request, HttpServletResponse response)
117             throws ServletException, IOException {
118         processRequest(request, response);
119     }
120   
121     /**
122      * Handles the HTTP
123      * <code>POST</code> method.
124      *
125      * @param request servlet request
126      * @param response servlet response
127      * @throws ServletException if a servlet-specific error occurs
128      * @throws IOException if an I/O error occurs
129      */
130     @Override
131     protected void doPost(HttpServletRequest request, HttpServletResponse response)
132             throws ServletException, IOException {
133         processRequest(request, response);
134     }
135   
136     /**
137      * Returns a short description of the servlet.
138      *
139      * @return a String containing servlet description
140      */
141     @Override
142     public String getServletInfo() {
143         return "Short description";
144     }// </editor-fold>
145 }

2. 通过getPart()、getParts()取得上传文件。

001 /**
002  * To change this template, choose Tools | Templates
003  * and open the template in the editor.
004  */
005 package net.individuals.web.servlet;
006   
007 import java.io.FileNotFoundException;
008 import java.io.FileOutputStream;
009 import java.io.IOException;
010 import java.io.InputStream;
011 import java.io.OutputStream;
012 import javax.servlet.ServletException;
013 import javax.servlet.annotation.MultipartConfig;
014 import javax.servlet.annotation.WebServlet;
015 import javax.servlet.http.HttpServlet;
016 import javax.servlet.http.HttpServletRequest;
017 import javax.servlet.http.HttpServletResponse;
018 import javax.servlet.http.Part;
019   
020 /**
021  *
022  * @author Barudisshu
023  */
024 @MultipartConfig
025 @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
026 public class UploadServlet extends HttpServlet {
027   
028     /**
029      * Processes requests for both HTTP
030      * <code>GET</code> and
031      * <code>POST</code> methods.
032      *
033      * @param request servlet request
034      * @param response servlet response
035      * @throws ServletException if a servlet-specific error occurs
036      * @throws IOException if an I/O error occurs
037      */
038     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
039             throws ServletException, IOException {
040         Part part = request.getPart("photo");
041         String fileName = getFileName(part);
042         writeTo(fileName, part);
043     }
044   
045     //取得上传文件名
046     private String getFileName(Part part) {
047         String header = part.getHeader("Content-Disposition");
048         String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
049   
050         return fileName;
051     }
052   
053     //存储文件
054     private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException {
055         InputStream in = part.getInputStream();
056         OutputStream out = new FileOutputStream("e:/workspace/" + fileName);
057         byte[] buffer = new byte[1024];
058         int length = -1;
059         while ((length = in.read(buffer)) != -1) {
060             out.write(buffer, 0, length);
061         }
062   
063         in.close();
064         out.close();
065     }
066   
067     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
068     /**
069      * Handles the HTTP
070      * <code>GET</code> method.
071      *
072      * @param request servlet request
073      * @param response servlet response
074      * @throws ServletException if a servlet-specific error occurs
075      * @throws IOException if an I/O error occurs
076      */
077     @Override
078     protected void doGet(HttpServletRequest request, HttpServletResponse response)
079             throws ServletException, IOException {
080         processRequest(request, response);
081     }
082   
083     /**
084      * Handles the HTTP
085      * <code>POST</code> method.
086      *
087      * @param request servlet request
088      * @param response servlet response
089      * @throws ServletException if a servlet-specific error occurs
090      * @throws IOException if an I/O error occurs
091      */
092     @Override
093     protected void doPost(HttpServletRequest request, HttpServletResponse response)
094             throws ServletException, IOException {
095         processRequest(request, response);
096     }
097   
098     /**
099      * Returns a short description of the servlet.
100      *
101      * @return a String containing servlet description
102      */
103     @Override
104     public String getServletInfo() {
105         return "Short description";
106     }// </editor-fold>
107 }

另一种较为简单的方法:

01 /**
02  * To change this template, choose Tools | Templates
03  * and open the template in the editor.
04  */
05 package net.individuals.web.servlet;
06   
07 import java.io.IOException;
08 import java.io.PrintWriter;
09 import javax.servlet.ServletException;
10 import javax.servlet.annotation.MultipartConfig;
11 import javax.servlet.annotation.WebServlet;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15 import javax.servlet.http.Part;
16   
17 /**
18  *采用part的wirte(String fileName)上传,浏览器将产生临时TMP文件。
19  * @author Barudisshu
20  */
21 @MultipartConfig(location = "e:/workspace")
22 @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
23 public class UploadServlet extends HttpServlet {
24   
25     /**
26      * Processes requests for both HTTP
27      * <code>GET</code> and
28      * <code>POST</code> methods.
29      *
30      * @param request servlet request
31      * @param response servlet response
32      * @throws ServletException if a servlet-specific error occurs
33      * @throws IOException if an I/O error occurs
34      */
35     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
36             throws ServletException, IOException {
37         //处理中文文件名
38         request.setCharacterEncoding("UTF-8");
39         Part part = request.getPart("photo");
40         String fileName = getFileName(part);
41         //将文件写入location指定的目录
42         part.write(fileName);
43     }
44   
45     private String getFileName(Part part) {
46         String header = part.getHeader("Content-Disposition");
47         String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
48         return fileName;
49     }
50   
51     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
52     /**
53      * Handles the HTTP
54      * <code>GET</code> method.
55      *
56      * @param request servlet request
57      * @param response servlet response
58      * @throws ServletException if a servlet-specific error occurs
59      * @throws IOException if an I/O error occurs
60      */
61     @Override
62     protected void doGet(HttpServletRequest request, HttpServletResponse response)
63             throws ServletException, IOException {
64         processRequest(request, response);
65     }
66   
67     /**
68      * Handles the HTTP
69      * <code>POST</code> method.
70      *
71      * @param request servlet request
72      * @param response servlet response
73      * @throws ServletException if a servlet-specific error occurs
74      * @throws IOException if an I/O error occurs
75      */
76     @Override
77     protected void doPost(HttpServletRequest request, HttpServletResponse response)
78             throws ServletException, IOException {
79         processRequest(request, response);
80     }
81   
82     /**
83      * Returns a short description of the servlet.
84      *
85      * @return a String containing servlet description
86      */
87     @Override
88     public String getServletInfo() {
89         return "Short description";
90     }// </editor-fold>
91 }

使用getParts()上传多个文件:

01 <!--
02 To change this template, choose Tools | Templates
03 and open the template in the editor.
04 -->
05 <!DOCTYPE html>
06 <html>
07     <head>
08         <title></title>
09         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
10     </head>
11     <body>
12         <div>
13             <form action="UploadServlet3" method="POST" enctype="multipart/form-data">
14                 <table>
15                     <tr>
16                         <td><label for="file1">文件1:</label></td>
17                         <td><input type="file" id="file1" name="file"></td>
18                     </tr>
19                     <tr>
20                         <td><label for="file2">文件2:</label></td>
21                         <td><input type="file" id="file2" name="file"></td>
22                     </tr>
23                     <tr>
24                         <td><label for="file3">文件3:</label></td>
25                         <td><input type="file" id="file3" name="file"></td>
26                     </tr>
27                     <tr>
28                         <td colspan="2"><input type="submit" value="上传" name="upload"></td>
29                     </tr>
30                 </table>
31             </form>
32         </div>
33     </body>
34 </html>
 

对应Servlet代码:

01 /**
02  * To change this template, choose Tools | Templates
03  * and open the template in the editor.
04  */
05 package net.individuals.web.servlet;
06   
07 import java.io.IOException;
08 import java.io.PrintWriter;
09 import javax.servlet.ServletException;
10 import javax.servlet.annotation.MultipartConfig;
11 import javax.servlet.annotation.WebServlet;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15 import javax.servlet.http.Part;
16   
17 /**
18  *
19  * @author Barudisshu
20  */
21 @MultipartConfig(location = "e:/workspace")
22 @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
23 public class UploadServlet extends HttpServlet {
24   
25     /**
26      * Processes requests for both HTTP
27      * <code>GET</code> and
28      * <code>POST</code> methods.
29      *
30      * @param request servlet request
31      * @param response servlet response
32      * @throws ServletException if a servlet-specific error occurs
33      * @throws IOException if an I/O error occurs
34      */
35     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
36             throws ServletException, IOException {
37         request.setCharacterEncoding("utf-8");
38         //迭代Collection中所有Part对象
39         for (Part part : request.getParts()) {
40             //只处理上传文件区段
41             if (part.getName().startsWith("file")) {
42                 String fileName = getFileName(part);
43                 part.write(fileName);
44             }
45         }
46     }
47   
48     private String getFileName(Part part) {
49         String header = part.getHeader("Content-Disposition");
50         String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
51         header.lastIndexOf("\"");
52         return fileName;
53     }
54   
55     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
56     /**
57      * Handles the HTTP
58      * <code>GET</code> method.
59      *
60      * @param request servlet request
61      * @param response servlet response
62      * @throws ServletException if a servlet-specific error occurs
63      * @throws IOException if an I/O error occurs
64      */
65     @Override
66     protected void doGet(HttpServletRequest request, HttpServletResponse response)
67             throws ServletException, IOException {
68         processRequest(request, response);
69     }
70   
71     /**
72      * Handles the HTTP
73      * <code>POST</code> method.
74      *
75      * @param request servlet request
76      * @param response servlet response
77      * @throws ServletException if a servlet-specific error occurs
78      * @throws IOException if an I/O error occurs
79      */
80     @Override
81     protected void doPost(HttpServletRequest request, HttpServletResponse response)
82             throws ServletException, IOException {
83         processRequest(request, response);
84     }
85   
86     /**
87      * Returns a short description of the servlet.
88      *
89      * @return a String containing servlet description
90      */
91     @Override
92     public String getServletInfo() {
93         return "Short description";
94     }// </editor-fold>
95 }

Servlet多文件上传方法的更多相关文章

  1. Servlet实现文件上传

    一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip      :   点击打开链接 2) commons- ...

  2. java常见3种文件上传速度对比和文件上传方法详细代码

    在java里面文件上传的方式很多,最简单的依然是FileInputStream.FileOutputStream了,在这里我列举3种常见的文件上传方法代码,并比较他们的上传速度(由于代码是在本地测试, ...

  3. Servlet实现文件上传,可多文件上传

    一.Servlet实现文件上传,需要添加第三方提供的jar包 接着把这两个jar包放到 lib文件夹下: 二: 文件上传的表单提交方式必须是POST方式, 编码类型:enctype="mul ...

  4. 配置servlet支持文件上传

    Servlet3.0为Servlet添加了multipart配置选项,并为HttpServletRequest添加了getPart和getParts方法获取上传文件.为了使Servlet支付文件上传需 ...

  5. jsp+servlet实现文件上传下载

    相关素材下载 01.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" ...

  6. java commons-fileupload servlet 多文件上传

    commons-fileupload servlet 多文件上传 需要引入的 jar 包. commons-fileupload-1.3.2.jar commons-io-2.2.jar 工程路劲:查 ...

  7. Servlet之文件上传

    上传表单中的注意事项: 表单 method 属性应该设置为 POST 方法,不能使用 GET 方法 表单 enctype 属性应该设置为multipart/form-data 下面的实例是借助于com ...

  8. 使用FileUpload实现Servlet的文件上传

    简介 FileUpload 是 Apache commons下面的一个子项目,用来实现Java环境下的文件上传功能. FileUpload链接 FileUpload 是基于Apache的Commons ...

  9. servlet实现文件上传,预览,下载和删除

      一.准备工作 1.1 文件上传插件:uploadify: 1.2 文件上传所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar 1.3 将数 ...

随机推荐

  1. asp.net mvc 在JS中跳转到其它controller/action

    平时在ASP.NET 中经常这样写, $('#loginOut').click(function() {           $.messager.confirm('系统提示', '您确定要退出本次登 ...

  2. 挂起的更改中的“解析”是什么意思?原来是微软错误的翻译

    [2017.4.5 补充] 收到微软TFS产品组的回复,由于版本分支丢失了本来已经修复的内容,并确认下一个版本将修复这个问题. 自从团队资源管理器的"挂起的更改中"可以链接相关工作 ...

  3. DevOps Workshop 研发运维一体化(广州站)

    第一天对软件开发的需求管理.项目计划和源代码管理进行的全面而深入的介绍,并且为到会的所有开发人员提供现场动手实验的机会,大家兴致高涨,按照我们的操作手册完成了所有实验课题. 第二天主要介绍了最新的自动 ...

  4. 关于C_Sharp集中处理异常

    1.写在前面 “异常意味着什么?”,想必不用对此做多余的解释,我们有理由相信在任何情况下任何应用程序都有可能出现异常,若在程序中没有对异常进行处理,则操作系统会以粗暴的方式处理掉它(弹出错误提示框), ...

  5. C#HttpUtility.UrlEncode 大写问题

    工作上和另一个公司对接,调对方的api需要用到md5加密,加密前要使用HttpUtility.UrlEncode,对方接口一直返回验证错误,定位了问题发现是中文编码使用HttpUtility.UrlE ...

  6. STM32F4时钟配置库函数详解

    在STM32中,所有的应用都是基于时钟,所以时钟的配置就尤为重要了,而不能仅仅只知道使用默认时钟. STM32F4的时钟树如上图所示,HSE为外部接入的一个8M的时钟,然后再给PLL提供输入时钟,经过 ...

  7. InnoDB之锁机制

    前两天听了姜老大关于InnoDB中锁的相关培训,刚好也在看这方面的知识,就顺便利用时间把这部分知识做个整理,方便自己理解.主要分为下面几个部分 1. InnoDB同步机制 InnoDB存储引擎有两种同 ...

  8. Android Locale

    Locale 是用来适配语言和地区的.在实际使用过程中,如果使用不当还是会出现错误. 首先,需要了解的是,Locale 分两种,一种是语言,一种是地区.语言比如英语,地区比如美国.区别显而易见,说英语 ...

  9. FreePascal - CodeTyphon交叉编译,在一个操作系统生成各个操作系统可以运行的程序!

    致谢:[XE3]MN,让我加快完成了使用CodeTyphon进行交叉编译! CodeTyphon版本: 6.0 下载:http://www.pilotlogic.com/codetyphon/zips ...

  10. 【洛谷p3994】Highway 二分+斜率优化DP

    题目大意:给你一颗$n$个点的有根树,相邻两个点之间有距离,我们可以从$x$乘车到$x$的祖先,费用为$dis\times P[x]+Q[x]$,问你除根以外每个点到根的最小花费. 数据范围:$n≤1 ...