[] Java Servlet file upload - no need to import another package Jar

Servlet3.0, the improvement of some of the API, simplifying Java Web development.

For example, file upload. The traditional file upload needs the help of tools such as common-fileupload, very complex, with Servlet3.0 the API is very simple.

Upload page upload.jsp / upload.html

    <form method="post" action="upload" enctype="multipart/form-data">
        选择文件:<input type="file" id="file" name="file"><br>
        <input type="submit" value="提交">
    </form>

Processing the uploaded Servlet

// Servlet3.0 configuration corresponding to the web.xml 
@WebServlet (name = "the Upload", urlPatterns = { "/ Upload" })
 // file upload annotations 
@MultipartConfig
 public  class the Upload the extends the HttpServlet {
     public  void the doPost (the HttpServletRequest Request, Response the HttpServletResponse)
             throws ServletException, IOException {
             // solve the Chinese garbled 
            the response.setContentType ( "text / HTML; charset = UTF-. 8" ); 
            Request.setCharacterEncoding ( "UTF-. 8" ); 
            the PrintWriter OUT = response.getWriter (); 
            File path= New new File ( "D: // tmp" );
             IF (! {Path.exists ()) 
                path.mkdir (); 
            } 
            Part Part = request.getPart ( "File" ); 
            Out.println ( "size:" part.getSize + () + "<br>" );
             // following the methods require tomcat7 get file name 
            String = part.getHeader CD ( "the Content-Disposition" );
             // taken of different types of files to decide if that 
            String cd.substring = filename (cd.lastIndexOf ( "=") + 2, cd.length () -. 1 );
             // above Tomcat8 only part.
getSubmittedFileName () method can directly obtain //             to upload files to the server
            String filePath = path.getPath() + File.separator + filename;
            part.write(filePath);
            System.out.println("File Upload : " + filePath);
    }

}

 

Guess you like

Origin www.cnblogs.com/to-red/p/11129451.html