Servlet 파일 업로드 의 세 가지 방법 요약

Servlet 파일 업로드 의 세 가지 방법 요약
1.getInputStream()을 통 해 업로드 파일 을 가 져 옵 니 다.

/** 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
package net.individuals.web.servlet; 
 
import java.io.DataInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
/** 
 * 
 * @author Barudisshu 
 */ 
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"}) 
public class UploadServlet extends HttpServlet { 
 
  /** 
   * Processes requests for both HTTP 
   * <code>GET</code> and 
   * <code>POST</code> methods. 
   * 
   * @param request servlet request 
   * @param response servlet response 
   * @throws ServletException if a servlet-specific error occurs 
   * @throws IOException if an I/O error occurs 
   */ 
  protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8"); 
    //    Body 
    byte[] body = readBody(request); 
    //    Body         
    String textBody = new String(body, "ISO-8859-1"); 
    //          
    String fileName = getFileName(textBody); 
    //            
    Position p = getFilePosition(request, textBody); 
    //      
    writeTo(fileName, body, p); 
  } 
 
  //    
  class Position { 
 
    int begin; 
    int end; 
 
    public Position(int begin, int end) { 
      this.begin = begin; 
      this.end = end; 
    } 
  } 
 
  private byte[] readBody(HttpServletRequest request) throws IOException { 
    //           
    int formDataLength = request.getContentLength(); 
    //  ServletInputStream      
    DataInputStream dataStream = new DataInputStream(request.getInputStream()); 
    byte body[] = new byte[formDataLength]; 
    int totalBytes = 0; 
    while (totalBytes < formDataLength) { 
      int bytes = dataStream.read(body, totalBytes, formDataLength); 
      totalBytes += bytes; 
    } 
    return body; 
  } 
 
  private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException { 
    //           
    String contentType = request.getContentType(); 
    String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length()); 
    //                 
    int pos = textBody.indexOf("filename=\""); 
    pos = textBody.indexOf("
", pos) + 1; pos = textBody.indexOf("
", pos) + 1; pos = textBody.indexOf("
", pos) + 1; int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4; int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length; int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length; return new Position(begin, end); } private String getFileName(String requestBody) { String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10); fileName = fileName.substring(0, fileName.indexOf("
")); fileName = fileName.substring(fileName.indexOf("
") + 1, fileName.indexOf("\"")); return fileName; } private void writeTo(String fileName, byte[] body, Position p) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream("e:/workspace/" + fileName); fileOutputStream.write(body, p.begin, (p.end - p.begin)); fileOutputStream.flush(); fileOutputStream.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
 2.getPart(),getParts()를 통 해 업로드 파일 을 가 져 옵 니 다.
    body 형식:

POST http://www.example.com HTTP/1.1  
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA  
 
------WebKitFormBoundaryrGKCBY7qhFd3TrwA  
Content-Disposition: form-data; name="text"  
 
title  
------WebKitFormBoundaryrGKCBY7qhFd3TrwA  
Content-Disposition: form-data; name="file"; filename="chrome.png"  
Content-Type: image/png  
 
PNG ... content of chrome.png ...  
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--  

 

[html] view plain copy
/** 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
package net.individuals.web.servlet; 
 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.MultipartConfig; 
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; 
 
/** 
 * 
 * @author Barudisshu 
 */ 
@MultipartConfig 
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"}) 
public class UploadServlet extends HttpServlet { 
 
  /** 
   * Processes requests for both HTTP 
   * <code>GET</code> and 
   * <code>POST</code> methods. 
   * 
   * @param request servlet request 
   * @param response servlet response 
   * @throws ServletException if a servlet-specific error occurs 
   * @throws IOException if an I/O error occurs 
   */ 
  protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    Part part = request.getPart("photo"); 
    String fileName = getFileName(part); 
    writeTo(fileName, part); 
  } 
 
  //        
  private String getFileName(Part part) { 
    String header = part.getHeader("Content-Disposition"); 
    String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\"")); 
 
    return fileName; 
  } 
 
  //     
  private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException { 
    InputStream in = part.getInputStream(); 
    OutputStream out = new FileOutputStream("e:/workspace/" + fileName); 
    byte[] buffer = new byte[1024]; 
    int length = -1; 
    while ((length = in.read(buffer)) != -1) { 
      out.write(buffer, 0, length); 
    } 
 
    in.close(); 
    out.close(); 
  } 
 
  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> 
  /** 
   * Handles the HTTP 
   * <code>GET</code> method. 
   * 
   * @param request servlet request 
   * @param response servlet response 
   * @throws ServletException if a servlet-specific error occurs 
   * @throws IOException if an I/O error occurs 
   */ 
  @Override 
  protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    processRequest(request, response); 
  } 
 
  /** 
   * Handles the HTTP 
   * <code>POST</code> method. 
   * 
   * @param request servlet request 
   * @param response servlet response 
   * @throws ServletException if a servlet-specific error occurs 
   * @throws IOException if an I/O error occurs 
   */ 
  @Override 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    processRequest(request, response); 
  } 
 
  /** 
   * Returns a short description of the servlet. 
   * 
   * @return a String containing servlet description 
   */ 
  @Override 
  public String getServletInfo() { 
    return "Short description"; 
  } 
} 

3.다른 간단 한 방법:part 의 wirte(String fileName)로 업로드 하면 브 라 우 저 는 임시 TMP 파일 을 생 성 합 니 다.

/** 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
package net.individuals.web.servlet; 
 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.MultipartConfig; 
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; 
 
/** 
 *  part wirte(String fileName)  ,        TMP  。 
 * @author Barudisshu 
 */ 
@MultipartConfig(location = "e:/workspace") 
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"}) 
public class UploadServlet extends HttpServlet { 
 
  /** 
   * Processes requests for both HTTP 
   * <code>GET</code> and 
   * <code>POST</code> methods. 
   * 
   * @param request servlet request 
   * @param response servlet response 
   * @throws ServletException if a servlet-specific error occurs 
   * @throws IOException if an I/O error occurs 
   */ 
  protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    //        
    request.setCharacterEncoding("UTF-8"); 
    Part part = request.getPart("photo"); 
    String fileName = getFileName(part); 
    //     location      
    part.write(fileName); 
  } 
 
  private String getFileName(Part part) { 
    String header = part.getHeader("Content-Disposition"); 
    String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\"")); 
    return fileName; 
  } 
 
  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> 
  /** 
   * Handles the HTTP 
   * <code>GET</code> method. 
   * 
   * @param request servlet request 
   * @param response servlet response 
   * @throws ServletException if a servlet-specific error occurs 
   * @throws IOException if an I/O error occurs 
   */ 
  @Override 
  protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    processRequest(request, response); 
  } 
 
  /** 
   * Handles the HTTP 
   * <code>POST</code> method. 
   * 
   * @param request servlet request 
   * @param response servlet response 
   * @throws ServletException if a servlet-specific error occurs 
   * @throws IOException if an I/O error occurs 
   */ 
  @Override 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    processRequest(request, response); 
  } 
 
  /** 
   * Returns a short description of the servlet. 
   * 
   * @return a String containing servlet description 
   */ 
  @Override 
  public String getServletInfo() { 
    return "Short description"; 
  }// </editor-fold> 
} 

이상 은 Servlet 이 파일 업로드 의 실례 를 실현 하 는 것 입 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남기 거나 본 사이트 의 커 뮤 니 티 에 가서 토론 을 교류 하 십시오.읽 어 주 셔 서 감사합니다. 여러분 께 도움 이 되 기 를 바 랍 니 다.본 사이트 에 대한 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기