Servlet实现文件上传的几种方法

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

[html] view plain copy

  1. /**  
  2.  * To change this template, choose Tools | Templates  
  3.  * and open the template in the editor.  
  4.  */  
  5. package net.individuals.web.servlet;  
  6.   
  7. import java.io.DataInputStream;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import javax.servlet.ServletException;  
  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.   
  16. /**  
  17.  *  
  18.  * @author Barudisshu  
  19.  */  
  20. @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})  
  21. public class UploadServlet extends HttpServlet {  
  22.   
  23.     /**  
  24.      * Processes requests for both HTTP  
  25.      * <code>GET</code> and  
  26.      * <code>POST</code> methods.  
  27.      *  
  28.      * @param request servlet request  
  29.      * @param response servlet response  
  30.      * @throws ServletException if a servlet-specific error occurs  
  31.      * @throws IOException if an I/O error occurs  
  32.      */  
  33.     protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
  34.             throws ServletException, IOException {  
  35.         response.setContentType("text/html;charset=UTF-8");  
  36.         //读取请求Body  
  37.         byte[] body = readBody(request);  
  38.         //取得所有Body内容的字符串表示  
  39.         String textBody = new String(body, "ISO-8859-1");  
  40.         //取得上传的文件名称  
  41.         String fileName = getFileName(textBody);  
  42.         //取得文件开始与结束位置  
  43.         Position p = getFilePosition(request, textBody);  
  44.         //输出至文件  
  45.         writeTo(fileName, body, p);  
  46.     }  
  47.   
  48.     //构造类  
  49.     class Position {  
  50.   
  51.         int begin;  
  52.         int end;  
  53.   
  54.         public Position(int begin, int end) {  
  55.             this.begin = begin;  
  56.             this.end = end;  
  57.         }  
  58.     }  
  59.   
  60.     private byte[] readBody(HttpServletRequest request) throws IOException {  
  61.         //获取请求文本字节长度  
  62.         int formDataLength = request.getContentLength();  
  63.         //取得ServletInputStream输入流对象  
  64.         DataInputStream dataStream = new DataInputStream(request.getInputStream());  
  65.         byte body[] = new byte[formDataLength];  
  66.         int totalBytes = 0;  
  67.         while (totalBytes < formDataLength) {  
  68.             int bytes = dataStream.read(body, totalBytes, formDataLength);  
  69.             totalBytes += bytes;  
  70.         }  
  71.         return body;  
  72.     }  
  73.   
  74.     private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {  
  75.         //取得文件区段边界信息  
  76.         String contentType = request.getContentType();  
  77.         String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());  
  78.         //取得实际上传文件的气势与结束位置  
  79.         int pos = textBody.indexOf("filename=\"");  
  80.         pos = textBody.indexOf("\n", pos) + 1;  
  81.         pos = textBody.indexOf("\n", pos) + 1;  
  82.         pos = textBody.indexOf("\n", pos) + 1;  
  83.         int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;  
  84.         int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;  
  85.         int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;  
  86.   
  87.         return new Position(begin, end);  
  88.     }  
  89.   
  90.     private String getFileName(String requestBody) {  
  91.         String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);  
  92.         fileName = fileName.substring(0, fileName.indexOf("\n"));  
  93.         fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\""));  
  94.   
  95.         return fileName;  
  96.     }  
  97.   
  98.     private void writeTo(String fileName, byte[] body, Position p) throws IOException {  
  99.         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()取得上传文件。

    body格式:

[html] view plain copy

  1. POST http://www.example.com HTTP/1.1   
  2. Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA   
  3.   
  4. ------WebKitFormBoundaryrGKCBY7qhFd3TrwA   
  5. Content-Disposition: form-data; name="text"   
  6.   
  7. title   
  8. ------WebKitFormBoundaryrGKCBY7qhFd3TrwA   
  9. Content-Disposition: form-data; name="file"; filename="chrome.png"   
  10. Content-Type: image/png   
  11.   
  12. PNG ... content of chrome.png ...   
  13. ------WebKitFormBoundaryrGKCBY7qhFd3TrwA--   


 

[html] view plain copy

  1. /**  
  2.  * To change this template, choose Tools | Templates  
  3.  * and open the template in the editor.  
  4.  */  
  5. package net.individuals.web.servlet;  
  6.   
  7. import java.io.FileNotFoundException;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.io.InputStream;  
  11. import java.io.OutputStream;  
  12. import javax.servlet.ServletException;  
  13. import javax.servlet.annotation.MultipartConfig;  
  14. import javax.servlet.annotation.WebServlet;  
  15. import javax.servlet.http.HttpServlet;  
  16. import javax.servlet.http.HttpServletRequest;  
  17. import javax.servlet.http.HttpServletResponse;  
  18. import javax.servlet.http.Part;  
  19.   
  20. /**  
  21.  *  
  22.  * @author Barudisshu  
  23.  */  
  24. @MultipartConfig  
  25. @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})  
  26. public class UploadServlet extends HttpServlet {  
  27.   
  28.     /**  
  29.      * Processes requests for both HTTP  
  30.      * <code>GET</code> and  
  31.      * <code>POST</code> methods.  
  32.      *  
  33.      * @param request servlet request  
  34.      * @param response servlet response  
  35.      * @throws ServletException if a servlet-specific error occurs  
  36.      * @throws IOException if an I/O error occurs  
  37.      */  
  38.     protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
  39.             throws ServletException, IOException {  
  40.         Part part = request.getPart("photo");  
  41.         String fileName = getFileName(part);  
  42.         writeTo(fileName, part);  
  43.     }  
  44.   
  45.     //取得上传文件名  
  46.     private String getFileName(Part part) {  
  47.         String header = part.getHeader("Content-Disposition");  
  48.         String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));  
  49.   
  50.         return fileName;  
  51.     }  
  52.   
  53.     //存储文件  
  54.     private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException {  
  55.         InputStream in = part.getInputStream();  
  56.         OutputStream out = new FileOutputStream("e:/workspace/" + fileName);  
  57.         byte[] buffer = new byte[1024];  
  58.         int length = -1;  
  59.         while ((length = in.read(buffer)) != -1) {  
  60.             out.write(buffer, 0, length);  
  61.         }  
  62.   
  63.         in.close();  
  64.         out.close();  
  65.     }  
  66.   
  67.     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">  
  68.     /**  
  69.      * Handles the HTTP  
  70.      * <code>GET</code> method.  
  71.      *  
  72.      * @param request servlet request  
  73.      * @param response servlet response  
  74.      * @throws ServletException if a servlet-specific error occurs  
  75.      * @throws IOException if an I/O error occurs  
  76.      */  
  77.     @Override  
  78.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  79.             throws ServletException, IOException {  
  80.         processRequest(request, response);  
  81.     }  
  82.   
  83.     /**  
  84.      * Handles the HTTP  
  85.      * <code>POST</code> method.  
  86.      *  
  87.      * @param request servlet request  
  88.      * @param response servlet response  
  89.      * @throws ServletException if a servlet-specific error occurs  
  90.      * @throws IOException if an I/O error occurs  
  91.      */  
  92.     @Override  
  93.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  94.             throws ServletException, IOException {  
  95.         processRequest(request, response);  
  96.     }  
  97.   
  98.     /**  
  99.      * 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.     }  
  107. }  


 

3、另一种较为简单的方法:采用part的wirte(String fileName)上传,浏览器将产生临时TMP文件

[html] view plain copy

  1. /**  
  2.  * To change this template, choose Tools | Templates  
  3.  * and open the template in the editor.  
  4.  */  
  5. package net.individuals.web.servlet;  
  6.   
  7. import java.io.IOException;  
  8. import java.io.PrintWriter;  
  9. 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. }  

猜你喜欢

转载自my.oschina.net/newchaos/blog/1619288