Servlet3.0 provides native support for file upload.
Use annotation @ multipartconfig to identify a Servlet as supporting file upload.
Servlet3.0 encapsulates the POST request of multipart/form-data into a part to operate the uploaded file through the part.
Form for uploading files:
<Form action = "uploadservlet" method = "Post" enctype = "multipart/form-Data"> <tr> <TD> <input type = "file" name = "file"> <br> <input type = "Submit"> </TD> </tr> </form>
Servlet for processing file uploads:
Package COM. cndatacom. servlet; import Java. io. file; 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; @ webservlet (name = "uploadservlet", urlpatterns = "/uploadservlet ") @ multipartconfig // identify servlet support file upload public class uploadservlet extends httpservlet {@ overrideprotected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {request. setcharacterencoding ("UTF-8"); response. setcharacterencoding ("UTF-8"); response. setcontenttype ("text/html; charset = UTF-8"); // storage path string storepath = request. getservletcontext (). getrealpath ("/uploadfile"); Part = request. getpart ("file"); // servlet3 does not provide a method to directly obtain the file name. It must be parsed from the request header. // obtain the request header string header = part. getheader ("content-disposition"); // get the file name string filename = parsefilename (header); // write the file to the specified path part. write (storepath + file. separator + filename); printwriter out = response. getwriter (); out. println ("uploaded successfully"); out. flush (); out. close ();}/*** parse the file name * Based on the Request Header. Format of the Request Header: Form-data; name = "file "; filename = "a.txt" * @ Param header * @ return */Public String parsefilename (string header) {return header. substring (header. lastindexof ("=") + 2, header. length ()-1 );}}
@ Multipartconfig attributes are optional:
Filesizethreshold: sets the threshold. When the threshold is reached, files are written to the disk.
Location: Set the file storage directory.
Maxfilesize: maximum value of a file that can be uploaded, in bytes.
Maxrequestsize: maximum value allowed by multipart/form-data requests.