Serverless File Uploads for Java

6 Minutes to Integrate

Overview

In this guide, you’ll learn how to add Uploadcare file handling routines to your Java applications. It will take you no longer than 5 minutes to get started with file uploads: you’ll only need the single Uploadcare library dependency in place.

Get an Uploadcare Account

The first thing you need is an Uploadcare account, Sign Up if you haven’t done so before. Navigate to your dashboard, create a new project or pick an existing one. Proceed to the “API Keys” section and find your project keys. You will need them to create a client for Java API.

Setup

First, update your Java project configuration by adding the Uploadcare library dependency, java-artifact. Its latest version can be found here.

To build with Maven add to pom.xml:

<dependency>
  <groupId>com.uploadcare</groupId>
  <artifactId>uploadcare</artifactId>
  <version>3.2.0</version>
</dependency>

To build with Gradle add to Gradle build file:

compile 'com.uploadcare:uploadcare:3.2.0'

Below is a short introduction to Uploadcare basic concepts and the way to handle your files and settings on the per-account basis. You may choose to skip this section and go directly to uploading features.

Basic Concepts

One of the core Uploadcare concepts is the project. Uploadcare projects serve as separate environments holding different sets of files and settings within a single account. A project may be tailored to meet extra security requirements or accept files from a specific area of your application.

To access your project-specific data with Java, you need a client. In fact, the concept of the client is similar to the project: both are identified by a pair of API Keys. You can learn more about Uploadcare projects here.

Create Client

You initialize an Uploadcare client by providing your Public and Secret API Keys:

Client client = new Client("publicKey", "privateKey");

Upload Files with FileUploader and UrlUploader

There are two ways to upload files with the Java Uploadcare Library Uploader interface:

Below are a couple of simple examples. Of note is the com.uploadcare.api.File#getOriginalFileUrl method which we expect to return a combination of UUID and an original file name with removed whitespaces.

@Test
void uploadFileWithUrlUploader_uploadedAndRequestedFilesShouldMatch() throws UploadFailureException {
  Uploader uploader = new UrlUploader(client, URL);
  File uploadedFile = uploader.upload();
  String uploadedFileId = uploadedFile.getFileId();

  File requestedByIdFile = client.getFile(uploadedFileId);

  then(requestedByIdFile.hasOriginalFileUrl()).isTrue();
  then(requestedByIdFile.getOriginalFileUrl().getRawPath())
          .contains(uploadedFileId);
  then(requestedByIdFile.getOriginalFilename()).isEqualToIgnoringCase(SHUTTERSTOCK_FILE_NAME);
  then(requestedByIdFile.getMimeType()).isEqualTo("image/jpeg");
  then(requestedByIdFile.isRemoved()).isFalse();
  then(requestedByIdFile.isStored()).isTrue();
  then(requestedByIdFile.getUploadDate()).isInSameHourAs(new Date());
}

@Test
void uploadFileWithFileUploader_uploadedAndRequestedFilesShouldMatch()
    throws UploadFailureException {
  java.io.File localFile = new java.io.File(Optional.ofNullable(getClass().getClassLoader()
      .getResource(LOCAL_FILE_NAME)).map(java.net.URL::getFile)
      .orElseThrow(RuntimeException::new));
  Uploader uploader = new FileUploader(client, localFile);
  File uploadedFile = uploader.upload();
  String uploadedFileId = uploadedFile.getFileId();

  File requestedByIdFile = client.getFile(uploadedFileId);

  then(requestedByIdFile.hasOriginalFileUrl()).isTrue();
  then(requestedByIdFile.getOriginalFileUrl().getRawPath()).contains(uploadedFileId);
  then(requestedByIdFile.getOriginalFilename()).isEqualToIgnoringCase(LOCAL_FILE_NAME);
  then(requestedByIdFile.isRemoved()).isFalse();
  then(requestedByIdFile.isStored()).isTrue();
  then(requestedByIdFile.getUploadDate()).isInSameHourAs(new Date());
}

Manage Project Data and Files Within Your Account

Simple Use Cases

With Client, you get a few utility methods to retrieve and handle the project-specific data, like fetching a file by a file id or listing all uploaded files for the project. Note, ids are Uploadcare UUIDs associated with files whenever they get uploaded.

Here’s a short example of navigating your files and retrieving 10 file names uploaded to your project after today’s midnight and matching some arbitrary pattern:

// Print 10 file names uploaded after today's midnight and matching regexp
client.getFiles().asList()
        .stream()
        .map(f -> new Pair<>(f.getOriginalFilename(), f.getUploadDate()))
        .filter(p -> p.getValue().after(Date.from(todayMidnight))
                && p.getKey().matches(FILENAME_STARTING_WITH_LETTERS_AND_HAVING_EXTENSION))
        .limit(10)
        .forEach(System.out::println);

Auto File Storing

With Uploadcare, there are two general policies for storing files: you can either keep uploaded files permanently or let them be wiped out every 24 hours.

The first policy is called “Auto File Storing.” This is a default behavior that can be further configured in project settings.

The second policy allows you to permanently store files explicitly by making API calls. In Java, these per-file controls are provided by both com.uploadcare.api.Client#saveFile taking a UUID as a parameter and com.uploadcare.api.File#save.

Transfer Files to Custom Storage

You can connect an Amazon S3 Bucket to your Uploadcare account as custom storage. There are cases when you want this behavior.

Please, refer to our docs for instructions on how to enable and configure the custom storage behavior.

With the Java library, you move files to custom storage via the com.uploadcare.api.Client#copyFile method. The same behavior can be achieved through our REST API.

Conclusion

In this quick guide, we provided an overview of the Java Uploadcare Library and its methods. Refer to the official Java library GitHub repo for further reading.

Questions?

We’re always happy to help with code, integration, and other stuff.
Search our site for more info or post your question in our Community Area.