Java image and video upload

Cloudinary provides an API for uploading images, videos, and any other kind of file to the cloud. Files uploaded to Cloudinary are stored safely in the cloud with secure backups and revision history. Cloudinary's APIs allow secure uploading from your servers, directly from your visitors' browsers or mobile applications, or fetched via remote public URLs.

Cloudinary's Java SDK wraps Cloudinary's upload API and simplifies the integration. Java methods are available for easily performing Java image and video uploads to the cloud and Java helper methods are available for uploading directly from a browser to Cloudinary.

This page covers common usage patterns for Java image and video upload with Cloudinary.

For details on all available upload options and parameters, see the Media upload documentation, and the upload method of the Upload API Reference.

Cloudinary's Upload widget provides an alternative to using a Cloudinary SDK to add upload functionality to your application, eliminating the need to develop in-house interactive upload capabilities. The upload widget is an interactive, feature rich, simple-to-integrate user interface that enables you to add Cloudinary upload support to your website. The widget can be easily embedded in your web application with just a few lines of JavaScript code. See the Upload widget documentation for detailed information.

Upload widget main screen

Server-side upload

You can upload images, videos, or any other raw file to Cloudinary from your Java code. Uploading is done over HTTPS using a secure protocol based on your account's api_key and api_secret parameters.

Java image upload

The following Java method uploads an image to the cloud:

Copy to clipboard
import com.cloudinary.Cloudinary;
Cloudinary cloudinary = new Cloudinary();
cloudinary.upload(fileRef, ObjectUtils.emptyMap());

The first parameter is the file source and the second one is a map Map<String,Object> of additional upload parameters. The result of this method call is the deserialized server response - again, Map<String,Object>. In case of a server error or an HTTP error a RuntimeException is thrown.

For example, uploading a local image file named my_image.jpg:

Copy to clipboard
File file = new File("my_image.jpg");
Map uploadResult = cloudinary.uploader().upload(file, ObjectUtils.emptyMap());

The file to upload can be specified as a local path, a remote HTTP or HTTPS URL, a whitelisted storage bucket (S3 or Google Storage) URL, a base64 data URI, or an FTP URL. For details, see File source options.

For a full list of the Upload method parameters, see the upload method in the Upload API reference.

Java video upload

You upload videos in exactly the same way as images. However, the Upload method supports uploading files up to 100 MB only. To upload larger videos, use the UploadLarge method, which uploads large files to the cloud in chunks.

The UploadLarge method has the identical signature and options as the Upload method, with the addition of an optional ChunkSize parameter (default 20 MB).

The following example uploads dog.mp4 to Cloudinary and stores it in a bi-level folder structure with the public ID dog_closeup. It also performs two eager transformations that resize the video to a square and a small rectangle.

Copy to clipboard
    ObjectUtils.asMap("resource_type", "video",
    "public_id", "myfolder/mysubfolder/dog_closeup",
    "eager", Arrays.asList(
        new EagerTransformation().width(300).height(300).crop("pad").audioCodec("none"),
        new EagerTransformation().width(160).height(100).crop("crop").gravity("south").audioCodec("none")),
    "eager_async", true,
    "eager_notification_url", ""));

Upload response

By default, uploading is performed synchronously. Once finished, the uploaded image is immediately available for transformation and delivery. You can also perform an asynchronous upload using the UploadAsync method. See Asynchronous API methods for more information.

An upload call returns a JSON object with content similar to the following:

Copy to clipboard

The response is automatically parsed and converted into a Map.

The response includes HTTP and HTTPS URLs for accessing the uploaded media asset as well as additional information regarding the uploaded asset: The Public ID, resource type, width and height, file format, file size in bytes, a signature for verifying the response and more.

Related topics

  • For more information on uploading media assets, see the Media upload documentation.
  • For details on all available upload parameters, see the upload method of the Upload API Reference.

Direct uploading from the browser

The upload samples mentioned above allows your server-side Java code to upload media assets to Cloudinary. In this flow, if you have a web form that allows your users to upload images or videos, the media file's data is first sent to your server and only then uploaded to Cloudinary.

A more efficient and powerful option is to allow your users to upload images and videos in your client-side code directly from the browser to Cloudinary instead of going through your servers. This method allows for faster uploading and better user experience. It also reduces load from your servers and reduces the complexity of your Java or Java EE applications.

You can upload directly from the browser using signed or unsigned calls to the upload endpoint, as shown in the Upload multiple files using a form examples.

Alternatively, you can use Cloudinary's jQuery plugin as described in the following sections.

For a full working example of using the jQuery upload plugin, see the Photo Album sample project.

For signed uploads from your client-side code, a secure signature must be generated in your server-side Java code. You can use the apiSignRequest method to generate SHA signatures:

Copy to clipboard
cloudinary.apiSignRequest(Map<String, Object> paramsToSign, String apiSecret);

jQuery uploading environment setup

Start by including the required JavaScript files - jQuery, Cloudinary's plugin and the jQuery-File-Upload plugin it depends on. These are available in the js folder of Cloudinary's JavaScript library.

Then you can directly include the JavaScript files:

Copy to clipboard
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.ui.widget.js"></script>
<script type="text/javascript" src="jquery.iframe-transport.js"></script>
<script type="text/javascript" src="jquery.fileupload.js"></script>
<script type="text/javascript" src="jquery.cloudinary.js"></script>

Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters.

Never expose your api_secret in public client-side code.

To set up Cloudinary's configuration, include the following line in your scripts section of a view:

Copy to clipboard
    $.cloudinary.config("cloud_name", "your_cloud_name");

Alternatively, if you're using the cloudinary-taglib library in a Java EE JSP view context you can use the jsconfig and jsinclude tags in your view to add necessary JS code. All necessary configuration options will be taken from your instance of the Cloudinary class. For example:

Copy to clipboard
<%@taglib uri="" prefix="cl" %>

This is equivalent to:

Copy to clipboard
<script src="javascripts/cloudinary/jquery.ui.widget.js"></script>
<script src="javascripts/cloudinary/jquery.iframe-transport.js"></script>
<script src="javascripts/cloudinary/jquery.fileupload.js"></script>
<script src="javascripts/cloudinary/jquery.cloudinary.js"></script>
<script type='text/javascript'>
    "cloud_name": "your_cloud_name",
    "api_key": "your_api_key",
    "private_cdn": false,
    "cdn_subdomain": false

You can override the location of JS files and also include more JS files to get more Cloudinary JS power:

Copy to clipboard
<cl:jsinclude base="https://your-local-host.domain/cloudinary_js/"

This is equivalent to:

Copy to clipboard
<script src="https://your-local-host.domain/cloudinary_js/jquery.ui.widget.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.iframe-transport.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.cloudinary.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/canvas-to-blob.min.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload-image.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload-process.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload-validate.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/load-image.all.min.js"></script>

The Cloudinary JavaScript library utilizes the Blueimp File Upload library to support uploading media directly from the browser. You must explicitly initialize this library:

Copy to clipboard
$(function() {
    if($.fn.cloudinary_fileupload !== undefined) {

Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.

This solution assumes placing cloudinary_cors.html in the root of your application, for example src/main/webapp/assets/. This file is required for iframe fallback upload and is available in the html folder of Cloudinary's JavaScript library.

jQuery upload file tag

Embed a file input tag in your HTML pages using the imageUploadTag method of the Uploader class available from a Cloudinary instance or as an upload tag from the taglib.

Copy to clipboard
Map options = ObjectUtils.asMap("resource_type", "auto");
Map htmlOptions = ObjectUtils.asMap("alt", "sample");
String html = cloudinary.uploader().imageUploadTag("image_id", options, htmlOptions);

The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.

Copy to clipboard
    <cl:upload resourceType="auto" fieldName="image_id" alt="sample"/>

When uploading is completed, the identifier of the uploaded image is set as the value of a hidden input field of your selected name (e.g., image_id' in the example above). The identifier looks like this:

Copy to clipboard

And may be parsed and validated like in the example below:

Copy to clipboard
// 'identifier' contains the value put in the hidden input field
// which includes the signature returned from Cloudinary.
StoredFile storedFile = new StoredFile();

if (!storedFile.getComputedSignature(cloudinary).equals(storedFile.getSignature())) {
throw new Exception("Invalid upload signature");
} else {
    // Successful result

You can then process the identifier received by the form submission and store it for later use as if you're using a standard server side uploading.

You can also hook to the cloudinarydone event of the jQuery plugin in order retrieve and add to the form submission any other data item which you find useful and is available in the JSON response object.

Copy to clipboard
$(document).ready(function() {
    .on("cloudinarydone", function (e, data) {
        // Data contains the response from Cloudinary
        // Lets add bytes to the form to process on server side:
        var form = $("#myform");
        form.append("<input type='hidden' name='bytes' value='"+data.bytes+"'/>");
        // We can also automatically submit the form if we want.
        $.post(form.attr("action"), form.serialize());

Having stored the image_id, you can now display a directly uploaded image in the same way you would display any other Cloudinary hosted image:

Copy to clipboard
String html = cloudinary.url().format("jpg").version(version).transformation(
    new Transformation().width(120).height(80).crop("fill")).imageTag(publicId, ObjectUtils.emptyMap());

or in a view:

Copy to clipboard
<cl:image format="jpg" width="120" height="80" crop="fill" src="${publicId}"/>

Additional jQuery uploading options

When uploading directly from the browser, you can still specify all the upload options available to server-side uploading.

For example, the following call performs direct uploading that will also tag the uploaded image, limit its size to given dimensions and generate a thumbnail eagerly. Also notice the custom HTML attributes.

Copy to clipboard
import java.util.Arrays;
Transformation incoming = new Transformation().crop("limit").width(1000).height(1000);
List<Transformation> eager = Arrays.asList(new Transformation().crop("fill").width(150).height(150));
Map options = ObjectUtils.asMap(
    "callback", customCorsLocation,
    "tags", "directly_uploaded",
    "transformation", incoming,
    "eager": eager,
    "resource_type", "auto"
Map htmlOptions = ObjectUtils.asMap("style", "margin-top: 30px");
String html = cloudinary.uploader().imageUploadTag("image_id", options, htmlOptions);


Copy to clipboard
<cl:upload fieldName="image_id" callback="${customCorsLocation}" tags="directly_uploaded"
    transformation="c_limit,w_1000,h_1000" eager="c_fill,w_150,h_150" resourceType="auto"/>

For the full list of parameters available for signed uploads, see the upload method in the Upload API reference.

For security reasons, only this limited set of parameters can be used in an unsigned upload request.

Directly uploading a video using jQuery

Client-side upload from the browser (signed upload)

The following example renders a direct file upload input field using the imageUploadTag helper method. Although the default resource_type for this method is auto, the video type is explicitly defined, and asynchronous eager transformations are used to generate adaptive bitrate streaming content. The html parameter is used to include standard HTML parameters (in this case, an id attribute) in the generated tag.

This example assumes you have already included and configured the jQuery files as described in Direct uploading from the browser.

Copy to clipboard
        com.cloudinary.utils.ObjectUtils.asMap("resource_type", "video",
            "eager", Arrays.asList(
                new EagerTransformation().format("m3u8").rawTransformation("sp_full_hd")),
            "eager_async", true,
            "eager_notification_url", "",
        com.cloudinary.utils.ObjectUtils.asMap("id", "my_upload_tag")

Client-side upload from the browser (unsigned upload)

The following example renders an unsigned direct file upload input field using the unsignedImageUploadTag helper method. The default resource_type for this method is auto, so it can be used for images, video, and raw files. The method defines a public_ID and tags for the uploaded file.

This example assumes you have already included and configured the jQuery files as described in Direct uploading from the browser. It also assumes that my_upload_preset is defined as an unsigned preset for your account.

Copy to clipboard
cloudinary.uploader().unsignedImageUploadTag("video_id", "my_upload_preset",
        com.cloudinary.utils.ObjectUtils.asMap("resource_type", "video",
            "public_id", "my_video",
            "tags", Arrays.asList("user_218", "screencast"),

Additional jQuery library features

Cloudinary's jQuery library also enables an enhanced uploading experience with options like showing a progress bar, displaying a thumbnail of the uploaded image, drag & drop support, uploading multiple files and more.

For example, bind to Cloudinary's cloudinarydone event if you want to be notified when an upload to Cloudinary has completed. You will have access to the full details of the uploaded image and you can display a cloud-generated thumbnail of the uploaded images using Cloudinary's jQuery plugin. The following code creates a 150x100 thumbnail of an uploaded image and updates an input field with the public ID of this image.

Copy to clipboard
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {  
      { format: data.result.format, version: data.result.version, 
        crop: 'fill', width: 150, height: 100 })
  return true;

You can find more details and options in the jQuery documentation.

Related topics

  • For more information on uploading media assets, see the Media upload documentation.
  • For details on all available upload parameters, see the upload method of the Upload API Reference.

✔️ Feedback sent!

Rate this page: