Servlet 3.0 improves some of the APIS, which greatly simplifies Java Web development. These include HttpServletRequest adding support for file uploads.

HttpServletRequest provides the following two methods to handle file uploads:

  1. Part getPart(String name); Get the file upload domain by name
  2. Collection getParts(); Get all file upload domains

 

Construct the form to upload the file

<form action="uploadServlet" method="post" enctype="multipart/form-data">Uploading files:<input type="file" name="file"/><br/>File Description:<input type="text" name="desc"/>
    <input type="submit"/>
</form>
Copy the code

 

use

Annotate @webServlet + @multipartConfig on servlets that need to handle file uploads

@WebServlet("/uploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {}Copy the code

 

Can pass javax.mail. Servlet. HTTP. It. GetPart (String name) method for Part object

 

Javax.servlet.http.Part interface method:

methods role
InputStream getInputStream() throws IOException; Get the uploaded input stream
String getContentType(); Get the content-type field value of the multipart form
String getName(); Gets the field name of the multipart form
String getSubmittedFileName(); If the part is a file, return the file name; Otherwise, null
long getSize(); Get the size of the part
void write(String fileName) throws IOException; Write files
void delete() throws IOException;
String getHeader(String name); Gets the value of the specified header
Collection getHeaders(String name); Get the full value of the header
Collection getHeaderNames(); Get all the header names

Note:

The getSubmittedFileName method may not get the file name correctly when testing in IE 10.

Internet Options > Security > Custom Levels > Others > Disable Include local directory paths when uploading files to the server