How to Upload Multiple Files to pdfRest with Java

Upload multiple files in one Java multipart request and capture their resource IDs.
Share this page

Follow this Java walkthrough to upload multiple files to pdfRest with the Upload Files API Tool. The example adds several files under repeated multipart file fields and maps the response entries back to those inputs. Along the way, you'll see which fields are needed to upload multiple files to pdfRest and how the response fits into later processing.

Why Upload Multiple Files to pdfRest with Java?

A batch workflow may need several source documents before it can merge, compare, or process them. A single upload call stages the files and returns IDs that subsequent requests can reference.

The Java sample appends each local file under the repeated file field. The output order corresponds to the uploaded parts, so applications should retain the returned filename-to-ID association.

Java Code Example

import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import okhttp3.*;
import org.json.JSONObject;

public class Upload {

  // By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  // For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
  // service by commenting out the URL above and uncommenting the URL below.
  // For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
  // private static final String API_URL = "https://eu-api.pdfrest.com";

  // Specify the paths to your file here, or as the arguments when running the program.
  private static final String[] DEFAULT_FILE_PATHS =
      new String[] {"/path/to/file1.pdf", "/path/to/file2.pdf"};

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    String[] inputFilePaths;
    if (args.length > 0) {
      inputFilePaths = args;
    } else {
      inputFilePaths = DEFAULT_FILE_PATHS;
    }

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

    for (String inputFilePath : inputFilePaths) {
      final File inputFile = new File(inputFilePath);
      final RequestBody inputFileRequestBody =
          RequestBody.create(inputFile, MediaType.parse("application/pdf"));
      bodyBuilder.addFormDataPart("file", inputFile.getName(), inputFileRequestBody);
    }

    RequestBody requestBody = bodyBuilder.build();

    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/upload")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client = new OkHttpClient().newBuilder().build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

Source: Java sample on GitHub.

Breaking Down the Code

Load the Java HTTP and JSON dependencies

import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import okhttp3.*;
import org.json.JSONObject;

The library group uses OkHttp for transport, dotenv for loading PDFREST_API_KEY, and org.json for structured request or response data.

Choose the input and load credentials

private static final String[] DEFAULT_FILE_PATHS =
      new String[] {"/path/to/file1.pdf", "/path/to/file2.pdf"};

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    String[] inputFilePaths;
    if (args.length > 0) {
      inputFilePaths = args;
    } else {
      inputFilePaths = DEFAULT_FILE_PATHS;
    }

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

    for (String inputFilePath : inputFilePaths) {
      final File inputFile = new File(inputFilePath);
      final RequestBody inputFileRequestBody =

The input is an array of file paths; supplying arguments replaces the entire default list before the upload body is assembled.

Build the multipart request body

final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

    for (String inputFilePath : inputFilePaths) {
      final File inputFile = new File(inputFilePath);
      final RequestBody inputFileRequestBody =
          RequestBody.create(inputFile, MediaType.parse("application/pdf"));
      bodyBuilder.addFormDataPart("file", inputFile.getName(), inputFileRequestBody);
    }

    RequestBody requestBody = bodyBuilder.build();

    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))

The Java sample appends each local file under the repeated file field. The output order corresponds to the uploaded parts, so applications should retain the returned filename-to-ID association. The multipart builder uses the form multipart type required for combining uploaded content with operation parameters.

Send the request to pdfRest

Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/upload")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client = new OkHttpClient().newBuilder().build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());

The authenticated call ties the body to its endpoint and applies the required Api-Key header before OkHttp sends it.

Read the API response

.build();
    try {
      OkHttpClient client = new OkHttpClient().newBuilder().build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);

Each uploaded file appears in the response files array with its resource ID; preserve the filename-to-ID relationship when later calls depend on input order.

Beyond the Tutorial

This tutorial showed how a Java application can upload multiple files to pdfRest. With that foundation, you can use batch upload for merge inputs, attachment workflows, document packets, and other multi-resource operations.

For production use, do not assume an ID based only on array position after the response leaves the upload layer; store each returned filename and resource ID together. Check that every expected file was accepted before starting a merge or another operation that requires the complete set.

Use API Lab to inspect the request and output from the Upload Multiple to pdfRest operation. For the complete set of options supported by Upload Multiple to pdfRest, consult the Upload Files API Tool documentation.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.