Summary of three methods of Servlet implementing file upload
1. Get the uploaded file through getInputStream().
/** * To change this template, choose Tools | Templates * and open the template in the editor. */ package ; import ; import ; import ; import ; import ; import ; import ; import ; /** * * @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 { ("text/html;charset=UTF-8"); //Read Request Body byte[] body = readBody(request); //Get the string representation of all Body content String textBody = new String(body, "ISO-8859-1"); //Get the uploaded file name String fileName = getFileName(textBody); //Get the file start and end positions Position p = getFilePosition(request, textBody); //Output to file writeTo(fileName, body, p); } //Construction class class Position { int begin; int end; public Position(int begin, int end) { = begin; = end; } } private byte[] readBody(HttpServletRequest request) throws IOException { //Get request text byte length int formDataLength = (); //Get ServletInputStream input stream object DataInputStream dataStream = new DataInputStream(()); byte body[] = new byte[formDataLength]; int totalBytes = 0; while (totalBytes < formDataLength) { int bytes = (body, totalBytes, formDataLength); totalBytes += bytes; } return body; } private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException { // Obtain file section boundary information String contentType = (); String boundaryText = (("=") + 1, ()); //Get the actual momentum and end position of the file transmission int pos = ("filename=\""); pos = ("\n", pos) + 1; pos = ("\n", pos) + 1; pos = ("\n", pos) + 1; int boundaryLoc = (boundaryText, pos) - 4; int begin = (((0, pos)).getBytes("ISO-8859-1")).length; int end = (((0, boundaryLoc)).getBytes("ISO-8859-1")).length; return new Position(begin, end); } private String getFileName(String requestBody) { String fileName = (("filename=\"") + 10); fileName = (0, ("\n")); fileName = (("\n") + 1, ("\"")); return fileName; } private void writeTo(String fileName, byte[] body, Position p) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream("e:/workspace/" + fileName); (body, , ( - )); (); (); } // <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. Get uploaded files through getPart() and getParts().
Body format:
POST 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="" Content-Type: image/png PNG ... content of ... ------WebKitFormBoundaryrGKCBY7qhFd3TrwA-- [html] view plain copy /** * To change this template, choose Tools | Templates * and open the template in the editor. */ package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * * @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 = ("photo"); String fileName = getFileName(part); writeTo(fileName, part); } //Get uploaded file name private String getFileName(Part part) { String header = ("Content-Disposition"); String fileName = (("filename=\"") + 10, ("\"")); return fileName; } //Storage files private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException { InputStream in = (); OutputStream out = new FileOutputStream("e:/workspace/" + fileName); byte[] buffer = new byte[1024]; int length = -1; while ((length = (buffer)) != -1) { (buffer, 0, length); } (); (); } // <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. Another simpler method: use part wire (String fileName) to upload, and the browser will generate a temporary TMP file.
/** * To change this template, choose Tools | Templates * and open the template in the editor. */ package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** *Upload with part of the wire (String fileName), the browser will generate a temporary TMP file. * @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 { //Process Chinese file names ("UTF-8"); Part part = ("photo"); String fileName = getFileName(part); //Write the file to the directory specified by location (fileName); } private String getFileName(Part part) { String header = ("Content-Disposition"); String fileName = (("filename=\"") + 10, ("\"")); 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> }
The above is an example of Servlet file upload. If you have any questions, please leave a message or go to the community of this website to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this website!