Servlet provides three methods for uploading files.

Source: Internet
Author: User
Tags tmp file

Servlet provides three methods for uploading files.

Summary of three methods for uploading files using Servlet

1. Get the uploaded file through 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"); // read the request Body byte [] body = readBody (request ); // get the String of all Body content to indicate String textBody = new String (body, "ISO-8859-1"); // get the name of the uploaded file String fileName = getFileName (textBody ); // get the start and end positions of the file. Position p = getFilePosition (request, textBody); // output to the file writeTo (fileName, body, p );} // construct 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 {// get the request text byte length int formDataLength = request. getContentLength (); // get the ServletInputStream input stream object 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 {// get the object segment Boundary Information String contentType = request. getContentType (); String boundaryText = contentType. substring (contentType. lastIndexOf ("=") + 1, contentType. length (); // obtain the momentum of the actually uploaded file and the ending position int pos = textBody. indexOf ("filename = \" "); pos = textBody. indexOf ("\ n", pos) + 1; pos = textBody. indexOf ("\ n", pos) + 1; pos = textBody. indexOf ("\ n", 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 ("\ n"); fileName = fileName. substring (fileName. indexOf ("\ n") + 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. Get the uploaded file through getPart () and getParts.

Body format:

POST http://www.example.com HTTP/1.1 Content-Type: multipart/form-data; boundary = ---- reply ------ response 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] vie W 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 ja Vax. 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 H TTP * <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);} // get the Upload File Name private String getFileName (Part part) {String header = part. getHeader ("Content-Disposition"); String fileName = header. substring (header. indexOf ("filename = \" ") + 10, header. lastIndexOf ("\" "); return fileName;} // storage file private void writeTo (String fileName, Part part) throws IOException, FileNotFoundException {InputStream I N = 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. Another simple method: Use the wirte (String fileName) of the part 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 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. httpServletRe Quest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. part;/*** upload using the wirte (String fileName) of the part. 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 the request for a Chinese file name. setCharacterEncoding ("UTF-8"); Part part = request. getPart ("photo"); String fileName = getFileName (part); // write the file to the part in the directory specified by location. 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>}

The above is an example of Servlet File Upload. If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article and hope to help you. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.