Media library widget

By integrating the Cloudinary Media Library widget into your CMS or any other web application, all your users can easily select images, videos, PDFs, or other stored raw files directly from a Cloudinary account and insert them in a way that exactly fits your application design, required behavior, and overall workflow.

The integration involves only a few lines of code and provides you (and your users) all the benefits of Cloudinary's responsive Media Library UI with its rich search capabilities and optimized media asset delivery.

Media library widget features

This JavaScript-based integration includes many configuration options, including:

  • Set the Media Library to open as a modal dialog or inline in your application
  • Control whether users can insert one asset at a time or many
  • Set up default transformations to be applied to all selected assets.
    This can be useful to ensure usage of consistent size, quality, format, or other optimization settings, adding a logo overlay, or other applying styles to ensure consistency of the media delivered via your application. If the user also defines transformations, the default transformations are applied (chained) to their transformations.
  • Determine the look and feel of the button that opens the media library
  • Enable users to seamlessly log in to Cloudinary via authentication signature (included) or via your organization's SAML-based SSO provider (premium feature).

Media Library widget demo

How to integrate the widget in your app

Integration overview

The following steps summarize the process of integrating the Cloudinary Media Library widget into a page in your application. Click the links for detailed implementation information.

  1. Include the Cloudinary JavaScript file - Include Cloudinary's all.js file in the page where you want to open the Media Library.
  2. Optional. Generate the authentication signature - To seamlessly and securely log a user into Cloudinary so that they can use the Media Library widget directly from the application hosting the widget, you can generate and pass an SHA-256 encrypted signature based on the cloud name, user name, a timestamp, and your account's API secret.
  3. Set the configuration options - When you call the method to initialize and/or open the Media Library widget, you pass it a set of configuration options. These options include the mandatory cloud_name and api_key options. Additionally, you can provide a number of optional parameters that control settings such as those described in the introduction above.
  4. Create your callback function - After a user selects media assets and closes the Media Library, the widget returns a JSON payload that includes the URL(s) of the selected asset(s) as well as other asset data such as file and pixel size, format, asset type (image, video, raw, etc), and more. You should create an insertHandler callback function that receives and handles this data to control how the selected assets will be integrated into your page.
  5. Instantiate and open the Media Library widget instance - Now that you've set up the configuration options, and created the callback function, you pass these to the createMediaLibrary or openMediaLibrary method, which instantiates, or instantiates and opens, the widget.
  6. Optional. Set up SAML authentication. As an alternative to generating and passing an authentication signature, you can enable (or require) your users to log in to Cloudinary via your SAML-based SSO provider. If your users already log in using SSO for the CMS or web app that will host the Media Library widget, this option can provide a seamless experience.
  7. Optional. Define the Cloudinary log out policy - You can log the user out of Cloudinary when they log out of your CMS, or at any time, using the Cloudinary logout endpoint.

1. Include the Cloudinary JavaScript file

Add the following line to the web page where you want to open the Media Library widget:

<script src="https://media-library.cloudinary.com/global/all.js"></script>

2. Optional. Generate the authentication signature

To seamlessly and securely log a user into Cloudinary so that they can use the Media Library widget directly from the application hosting the widget, you can generate and pass an SHA-256 encrypted signature based on the cloud name, user name, a timestamp, and your account's API secret.

Note
Without either this option or the SAML authentication option configured, your users will need to separately log into Cloudinary when the widget opens, unless they have previously logged in via the Cloudinary console.

  1. Create a string with the parameters and values to sign in the format:
    cloud_name=value&timestamp=unixtime&username=clduser@domain.comapisecret

    • The parameters are listed in alphabetical order. Parameter names are separated from their values with =. Parameter/value pairs are joined with &.
    • apisecret in the syntax above represents your account API secret, appended directly after the last parameter without a separator.
    • unixtime indicates the exact time (in UNIX format) when the signature will become valid. The signature can be used to initialize the widget (and log into Cloudinary) for up to 1 hour after the timestamp value, so make sure the timestamp value will be calculated close to the time of widget instantiation. Once the user is logged in, their session will remain active with no expiration time. (Use the logout endpoint to log a user out of the Cloudinary account.)


      For example: "cloud_name=my_company&timestamp=1518601863&username=jane@mycompany.comabcd"

  2. Encrypt the signature string using SHA-256 hexadecimal hashing.
    For example, the above string results in: 764F932E9F6516637384D948E71B8DA6144F776083DDB66907BA4F25C70CB5C2.

Important
Because your signature includes your account's API secret, make sure to generate the signature in a secure place (not client-side).

3. Set the configuration options

When you call the openMediaLibrary() or createMediaLibrary() method, you pass it a set of configuration options. These options include the mandatory cloud_name and api_key options. Additionally, you can include a variety of optional settings that control the behavior and look and feel of the widget, as shown below.

You can also optionally adjust the values of the Media library behavior options shown below when re-opening the widget using the show() method.

Option Description Default Value
Authentication
cloud_name Required. The cloud_name of the account to access.
api_key Required. The account API key.
username The user name to use when logging in to the account.

When this value is provided, but the timestamp and signature are not, then if the user is not already logged in, the Cloudinary login screen opens with the specified user name already displayed.
When not provided, the user can manually enter any user name and corresponding password in the Cloudinary login screen.

If using an authentication signature, this value is required.
None
timestamp Relevant only if if using authentication signature login.

The Unix time in seconds at which the provided signature becomes valid.

The signature remains valid for 1 hour from the timestamp until login. Once the user is logged in, their session will remain active with no expiration time. (Use the logout endpoint to log a user out of the Cloudinary account.)
None.
signature Relevant only if if using authentication signature login.

An SHA-256 encrypted hash of the login credentials.
None.
Client-side
button_caption The caption text to display on the button in the page that opens the Media Library.

Applied when the btnPlaceholder parameter is provided in the widget instantiation method.

Open Media Library
button_class The class to use for the button in the page that opens the Media Library.

Applied when the btnPlaceholder parameter is provided in the widget instantiation method.

None.
(Uses a default HTML button element.)
inline_container The selector string or HTMLElement that will contain the Media Library widget. Include this parameter if you want the Media Library to open as an embedded element in your web page.

When opened as modal (default), the Media Library blocks access to your application page. When opened inline, your application is not blocked.
None
(opens as a modal dialog box)
z_index Sets the CSS stack order of the Media Library element.

Relevant when working with the Media Library widget as a modal dialog
(when inline_container is not defined).

99999 (top)
Media library behavior These options can be adjusted using the show() method.
default_transformations A transformation object containing one or more transformations that you want to apply to every inserted media asset. This is defined in the same way you would define an eager transformation. For example: [{quality: "auto"},{format: "auto"}]

Your default transformation can also be a complex, chained transformation object that controls the size and quality, adds overlays, and more. Additionally, it can contain more than one transformation definition. In that case, multiple derived images are created for each selected asset and included in the response.

Notes:
  • If the user selects a transformation from the asset drill-down page, your default transformation is chained after the user's transformation.
  • If your library includes multiple media types (image, video, raw), make sure that your default transformation works well on all relevant types.
None
max_files Max number of media assets that can be added during a single session. Relevant when multiple=true. 20
multiple Boolean. Whether to allow users to select multiple images from the Media Library asset grid. True

Sample configuration options definition

The configuration below displays a custom designed button (of class myBtn) with the label Insert Image or Video in the CMS or Web app page. When the button is clicked, the Media Library widget will open as a modal dialog with alex as the logged in user. For each image selected, a derived image will be generated with q_auto and f_auto transformations applied.

    const mloptions = {
        cloud_name: 'my_company',
        api_key: '12345',
        username: 'alex@mycompany.com',
        timestamp: '1234567890',
        signature: 'abcdefgh',
        button_class: 'myBtn',
        button_caption: 'Insert Image or Video',
        default_transformations: [{quality: "auto"},{format: "auto"}],    
        }

4. Create your callback function

After a user selects media assets and closes the the Media Library, the widget returns a JSON payload that includes the URL(s) of the selected asset(s), any derived assets based on specified or default transformations, as well as other asset data such as file dimensions, byte size, format, asset type (image, video, raw, etc), and more. You should create an insertHandler callback function that receives and handles this data to control how the selected assets will be integrated into your page.

For example: function insertHandler(data){...}

The returned data consists of an array of Objects (for each inserted asset). Each object has the following structure:

  • bytes: number
  • context: Object[]
  • created_at: string
  • derived: Object[]
  • format: string
  • height: number
  • public_id: string
  • resource_type: string
  • secure_url: string
  • tags: string[]
  • type:"upload"
  • url: string
  • version: number
  • width: number
  • [duration: number] - for video assets only

Sample JSON response for a transformed image

The following shows an example of the JSON data returned after a user applied a transformation on an image. Note that data includes the URLs (HTTP and HTTPS versions) of the original image as well as the URLs of the derived (transformed) image.

{
  assets: [{
  "public_id": "sample",
  "resource_type": "image",
  "type": "upload",
  "format": "jpg",
  "version": 1511474034,
  "url": "http://res.cloudinary.com/demo/image/upload/v1511474034/sample.jpg",
  "secure_url": "https://res.cloudinary.com/demo/image/upload/v1511474034/sample.jpg",
  "width": 864,
  "height": 576,
  "bytes": 120257,
  "duration": null,
  "tags": [],
  "context": [],
  "created_at": "2017-11-23T21:53:54Z",
  "derived": [
    {
      "url": "http://res.cloudinary.com/demo/image/upload/c_scale,e_grayscale,f_auto,q_auto,w_100/v1511474034/sample.jpg",
      "secure_url": "https://res.cloudinary.com/demo/image/upload/c_scale,e_grayscale,f_auto,q_auto,w_100/v1511474034/sample.jpg"
    }
  ]
}]}

Sample JSON response for an original video

The following shows an example of the JSON data returned after a user selected a video asset.

{ 
  assets: [{
  "public_id": "video_test/dog",
  "resource_type": "video",
  "type": "upload",
  "format": "mp4",
  "version": 1498600792,
  "url": "http://res.cloudinary.com/demo/video/upload/v1498600792/video_test/dog.mp4",
  "secure_url": "https://res.cloudinary.com/demo/video/upload/v1498600792/video_test/dog.mp4",
  "width": 854,
  "height": 480,
  "bytes": 9094354,
  "duration": 13.4134,
  "tags": [],
  "context": [],
  "created_at": "2017-06-27T21:59:52Z"
}, [...]]}

5. Instantiate and open the Media Library widget

Now that you've set up the configuration options, and created the callback function, you pass these to one of the instantiation methods. Both methods instantiate the widget.

  • openMediaLibrary - Instantiates the widget and then opens it. If the user is not yet logged into Cloudinary (either directly or via SSO), a link prompts the user to log in. After successful login, the widget opens and displays the available assets.
  • createMediaLibrary - Instantiates the widget, but does not open it. This can be useful if you want to activate the instantiation process in the background so that the Media Library will open more quickly for your users when requested. You can explicitly open or close the media widget using the show() and hide() toggle methods.
Syntax
  • openMediaLibrary(options, callback, [:btnPlaceholder])
  • createMediaLibrary(options, callback, [:btnPlaceholder])
Parameters
  • options - The configuration options to apply to your initial Media Library instance. If you use the show() and hide() toggle methods](#showorhidethemedia_library), you can optionally adjust some of these settings each time the widget opens.
  • callback - The callback function that determines how to handle the selected (returned) media assets.
  • btnPlaceholder - Optional. An HTMLElement or selector in your web page that will be replaced with a new button that toggles the Media Library instance open and closed. You can configure the appearance and text of this button by defining the button_class and button_caption configuration options.
Example
window.ml = cloudinary.createMediaLibrary(config, {insertHandler: insertHandler}, "#my_btn")

Show or hide the media library

After the Media Library has been instantiated, you can use the show() and hide() methods to open and close the widget in your application.

  • window.ml.show( [options] ) - If you want to adjust any of the Media Library behavior options that were defined when you instantiated the widget, you can optionally pass a new options object with the settings you want to change for this particular show session.

    For example, if you want to control the total number of assets a user can insert during a single operation in your CMS application, then if the user inserts a few items, closes the widget, and then reopens it, you might want to adjust the max_files value according to the new remaining amount.

    When calling show(), if the user is not yet logged into Cloudinary (either directly or via authentication signature/SSO), the user is prompted to log in.

  • window.ml.hide() - When you hide the widget, any adjusted options that were passed in the show() command are forgotten, and the settings revert to those set in the initial instantiation.

6. Optional. Set up SAML authentication

If your CMS or web app users already log in using SSO, you can also set up SSO login for Cloudinary so that your users can enjoy a seamless experience.

Note

  • Without either this option or the authentication signature option configured, your users will need to separately log into Cloudinary when the widget opens, unless they have previously logged in via the Cloudinary console.
  • SAML authentication is a premium Cloudinary feature. Contact us to enable this feature for your account.

After the feature has been made available for your account, you (as a Cloudinary account admin) activate SAML authentication for your users by entering your provider's SAML metadata URL in the SAML login option in the User settings of the Cloudinary console. You can choose to either allow or enforce SSO login for your users.

7. Optional. Define the Cloudinary log out policy

You can log the user out of Cloudinary when they log out of your application (or at any other point during their application session) by calling the Cloudinary logout endpoint: https://cloudinary.com/users/logout

Tip
When a user logs in or out of Cloudinary, it applies to both the Media Library widget and the full Cloudinary console (within in all tabs on the same device and browser session). For example, if a user is logged into an account via the Media Library widget and then opens the Cloudinary console in another tab and logs out or logs into another account, those changes will also apply to the still open Media Library widget in the other tab.

Examples

Example 1

The following example instantiates the Media Library widget as a modal dialog and prepares it for John Doe to log into the my_company Cloudinary account. (The login will either be handled by SAML authentication or manual login.) The configuration includes a customized button class and button text that will replace the open-btn HTML element in the CMS page. The data for the selected asset is displayed in the console log.

window.ml = cloudinary.createMediaLibrary({
   cloud_name: 'my_company',
   api_key: '1234567890',
   username: 'john_doe@mycompany.com',
   button_class: 'myBtn',
   button_caption: 'Select Image or Video',
 }, {
     insertHandler: function (data) {
       data.assets.forEach(asset => { console.log("Inserted asset:",
       JSON.stringify(asset, null, 2)) })
       }
    },
    document.getElementById("open-btn")
)

Example 2

The following example instantiates the Media Library widget and prepares it for Alice Wonderlin to log into the my_company Cloudinary account using an authentication signature, and then opens the widget as a modal dialog.

No Open Media Library button is created. The widget will enable this user to select up to 8 media assets. The data for each of the selected assets is displayed in the console log.

window.ml = cloudinary.openMediaLibrary({
  cloud_name: 'my_company',
  api_key: '1234567890',
  username: 'Alice_Wonderlin@mycompany.com',
  timestamp: '1234567890',
  signature: 'abcdefgh',
  inline_container: '.cms-container',
  multiple: true,
  max_files: 8,
  }, {
       insertHandler: function (data) {
         data.assets.forEach(asset => { console.log("Inserted asset:", 
           JSON.stringify(asset, null, 2)) })
       }
     }
  )