This example demonstrates how to do multipart upload using the Apache HttpClient library. In this example we upload a single file. We start by creating an object of the file to be uploaded. The FileBody represent the binary body part of the file.
Next, prepare the HttpEntity object by create an instance of MultipartEntityBuilder. Add parts to this object, in this case we add the fileBody. We can add multiple part to this object as the name says. It can be string, file, etc. as we do in a normal web form.
The build() method of the builder object finalize the entity creation and return us the HttpEntity object. To send / upload to server we create an HttpPost request and set the entity to be posted. Finally, the execute() method of the HttpClient object send the multipart object to server.
This example using the Apache Commons FileUpload library to create a simple application for uploading files. The program is divided into two parts, a form using JSP and a servlet for handling the upload process. To run the sample you need to download the Commons FileUpload and Commons IO get the latest stable version.
Commons FileUpload Demo
The first step is to create the upload form. The form contains two fields for selecting file to be uploaded and a submit button. The form should have an enctype attribute and the value is multipart/form-data. We use a post method and the submit process is handled by the upload-servlet as defined in the action attribute.
The second step is to create the servlet. The doPost method checks to see if the request contains a multipart content. After that we create a FileItemFactory, in this example we use the DiskFileItemFactory which is the default factory for FileItem. This factory creates an instance of FileItem and stored it either in memory or in a temporary file on disk depending on its content size.
The ServletFileUpload handles multiple files upload that we’ve specified in the form above sent using the multipart/form-data encoding type. The process of storing the data is determined by the FileItemFactory passed to the ServletFileUpload class.
The next steps is to parse the multipart/form-data stream by calling the ServletFileUpload.parseRequest(HttpServletRequest request) method. The parse process return a list of FileItem. After that we iterate on the list and check to see if FileItem representing an uploaded file or a simple form field. If it is represents an uploaded file we write the FileItem content to a file.