Handle post multipart is quite simple with languages like PHP. But what about if you develop your forms with JEE, including Servlets & JSP?
Here is some procedures and advices to understand how to handle post multipart form with JEE.
The API we will use is called FileUpload from Apache commons API.
As usual, some web resources about this API:
- Apache FileUpload main page
- … Where you can find the user guide
- … And some JavaDoc
You can download the latest version of this FileUpload API (1.2.1 – 18 January 2008) using this link. Simply add the .jar library to your Eclipse Project to use it.
The first thing is to create our JSP file, which will contain our form:
...
<%= request.getAttribute("message") %>
<form action="." enctype="multipart/form-data" method="post">
<input accept="image/*" name="file" type="file" />
<input type="submit" value="Send" />
</form>
...
Then, write the web.xml deployment descriptor as following in order to map correctly our servlet.
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!-- WebApp Name --> <display-name>MyPostServlet</display-name> <!-- Servlet declaration --> <servlet> <servlet-name>post</servlet-name> <servlet-class>foo.post.Servlet</servlet-class> </servlet> <!-- Servlet url mapping --> <servlet-mapping> <servlet-name>post</servlet-name> <url-pattern>/post</url-pattern> </servlet-mapping> <!-- Default welcome page --> <welcome-file-list> <welcome-file>post</welcome-file> </welcome-file-list> </web-app>
We can now create our main servlet which will handle GET and POST requests:
- The doGet method simply dispatch to our form.jsp,
- The doPost method parse the multipart request and then… call the doGet method.
Before process the post as a multipart one, you have to test it (see line 21).
When you parse the multipart post request with the ServletFileUpload.parseRequest(req) method, you get a List as return (see line 37).
Finally, loop with an Iterator to get all the FileItem of the request (see line 43).
public class Servlet extends HttpServlet {
private static final String CACHE_PATH = "./temp/";
private static final int CACHE_SIZE = 100*(int)Math.pow(10,6);
private static final int MAX_REQUEST_SIZE = 10*(int)Math.pow(10,6);
private static final int MAX_FILE_SIZE = 1*(int)Math.pow(10,6);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Redirecting to the test form
req.getRequestDispatcher("form.jsp").forward(req, resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(req))
{
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setRepository(new File(CACHE_PATH));
factory.setSizeThreshold(CACHE_SIZE);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
upload.setFileSizeMax(MAX_FILE_SIZE);
// Parse the request
@SuppressWarnings("unchecked")
List<FileItem> items = upload.parseRequest(req);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();
if (item.isFormField())
{
// The FileItem is a (text) form field
// You can save it to a database
}
else
{
// The FileItem is a file
// You can write it on the disk
}
}
}
// Add a validation message to the request
req.setAttribute("message","The file was uploaded");
// Redirect as a GET request to print the form again
doGet(req,resp);
}
}
0 Comments.