The FileUpload component remedies this situation, and in very few lines of code you can easily manage the files uploaded and store them in appropriate locations. You will now see an example where you upload some files first using a standard HTML form and then using HttpClient code.
Using HTML File Upload
The commonly used methodology to upload files is to have an HTML form where you define the files you want to upload. A common example of this HTML interface is the Web page you encounter when you want to attach files to an email while using any of the popular Web mail services.
In this example, you will create a simple HTML page where you provide for three files to be uploaded. Listing 9-4 shows the HTML for this page. Note that the enctype attribute for the form has the value multipart/form-data, and the input tag used is of type file. Based on the value of the action attribute, on form submission, the data is sent to ProcessFileUpload.jsp.
Listing 9-4. UploadFiles.html
Upload Files
You can use a servlet to handle the file upload. I have used JSP to minimize the code you need to write. The task that the JSP has to accomplish is to pick up the files that are sent as part of the request and store these files on the server. In the JSP, instead of displaying the result of the upload in the Web browser, I have chosen to print messages on the server console so that you can use this same JSP when it is not invoked through an HTML form but by using HttpClient-based code.
Listing 9-5 shows the JSP code. Note the code that checks whether the item is a form field. This check is required because the Submit button contents are also sent as part of the request, and you want to distinguish between this data and the files that are part of the request. You have set the maximum file size to 1,000,000 bytes using the setSizeMax method.
Listing 9-5. ProcessFileUpload.jsp
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>
html>
<% System.out.println("Content Type ="+request.getContentType()); DiskFileUpload fu = new DiskFileUpload(); // If file size exceeds, a FileUploadException will be thrown fu.setSizeMax(1000000); List fileItems = fu.parseRequest(request); Iterator itr = fileItems.iterator(); while(itr.hasNext()) { FileItem fi = (FileItem)itr.next(); //Check if not form field so as to only handle the file inputs //else condition handles the submit button input if(!fi.isFormField()) { System.out.println("nNAME: "+fi.getName()); System.out.println("SIZE: "+fi.getSize()); //System.out.println(fi.getOutputStream().toString()); File fNew= new File(application.getRealPath("/"), fi.getName()); System.out.println(fNew.getAbsolutePath()); fi.write(fNew); } else { System.out.println("Field ="+fi.getFieldName()); } } %>
Upload Successful!!