How do I do multipart upload using HttpClient?

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.

package org.kodejava.apache.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.File;
import java.io.IOException;

public class HttpPostMultipartExample {
    public static void main(String[] args) {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            File file = new File("data.zip");
            FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addPart("file", fileBody);
            HttpEntity entity = builder.build();

            HttpPost request = new HttpPost("http://localhost:8080/upload");
            request.setEntity(entity);
            client.execute(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To receive the file on the server you can take a look at the servlet code in the following example: How do I create a web based file upload?.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.14</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.14</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create a web based file upload?

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

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.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>File Upload</title>
</head>

<body>
<h1>File Upload Form</h1>
<hr/>
<form action="${pageContext.request.contextPath}/upload-servlet"
      method="post" enctype="multipart/form-data">

    <fieldset>
        <legend>Upload File</legend>
        <label for="filename_1">File: </label>
        <input id="filename_1" type="file" name="filename_1" size="50"/><br/>
        <label for="filename_2">File: </label>
        <input id="filename_2" type="file" name="filename_2" size="50"/><br/>
        <br/>
        <input type="submit" value="Upload File"/>
    </fieldset>

</form>
</body>
</html>

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.

So here is the FileUploadDemoServlet.

package org.kodejava.commons.fileupload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Serial;
import java.util.List;

@WebServlet(urlPatterns = "/upload-servlet")
public class FileUploadDemoServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List<FileItem> items = upload.parseRequest(request);
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        String fileName = item.getName();

                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/uploads");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.5</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I upload file to FTP server?

This example demonstrates how to upload file to FTP server.

package org.kodejava.commons.net;

import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.io.InputStream;

public class FTPUploadDemo {
    public static void main(String[] args) {
        FTPClient client = new FTPClient();
        String filename = "data.txt";

        // Read the file from the resources folder.
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try (InputStream is = classLoader.getResourceAsStream(filename)) {
            client.connect("ftp.example.com");
            boolean login = client.login("demo", "password");
            if (login) {
                System.out.println("Login success...");

                // Store file to server
                client.storeFile(filename, is);
                client.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.10.0</version>
</dependency>

Maven Central