![]() |
VOOZH | about |
Servlets are the server-side programs used to create dynamic web pages. They can be used to upload files on the server. This article shows two approaches for uploading multiple files on the server.
index.jsp
1. application/x-www-form-urlencoded (the default)
2. multipart/form-data
3. text/plain
In order to send files through HTML form, 'multipart/form-data' is used.
web.xml
File upload using cos.jar
Before Java EE 6, separate jar files like Apache's commons-fileupload were required to enable file upload functionalities in the application. Given below is an example to demonstrate the same.
Download cos.jar from the below link: https://jar-download.com/maven-repository-class-search.php?search_box=com.oreilly.servlet.MultipartRequest
FileUploadServlet.java
MultipartRequest is a utility class present in cos.jar which is used to handle the multipart data received from HTML form. It reads the files and saves them directly to the disk in the constructor itself.
It provides several constructors to specify the upload path, file size, etc.
- MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory)
- MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory, int maxPostSize)
It can also be used to get parameters using the following method :
java.lang.String getParameter(java.lang.String name)
File upload using Servlet 3.x API
@MultipartConfig annotation is provided to handle multipart data. It consists of the following parameters:
Part is an interface that represents a part or form item that was received within a multipart/form-data POST request. Useful methods of a Part interface are :
- void delete()
- InputStream getInputStream()
- void write(String fileName)
The following methods of HttpServletRequest are used to obtain Part objects:
- Part getPart(java.lang.String name)
- java.util.Collection<Part> getParts()
FileUploadServlet.java