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.

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, and whether they can apply transformations on their selected asset
  • Set up default transformations to be applied to all selected assets. This can be useful to ensure usage of consistent quality, format, or other optimization settings, adding a logo overlay, or other applying styles to ensure consistency of the media delivered via your application.
  • Determine the look and feel of the button that opens the media library
  • Enable users to seamlessly log in to Cloudinary via your organization's SAML-based SSO provider. (Premium feature)

Media Library widget demo

Integration instructions

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. 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, api_key, and username. Additionally, you can provide a number of optional parameters that control settings such as those described in the introduction above.
  3. 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.
  4. 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.
  5. Optional. Set up SAML authentication. 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.
  6. 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. 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, api_key, and usernameoptions. Additionally, you can include a variety of optional settings that control the behavior and look and feel of the widget.

The following configuration options are available:

Option Description Default Value
cloud_name Required. The cloud_name of the account to access.
api_key Required. The account API key.
username Required. The user name to use when logging in to the account.
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.)
default_transformations A transformation object containing one or more transformations that you want to apply to every inserted media asset. This is the same as applying an eager transformation to all the assets. For example: [{quality: "auto"},{format: "auto"}]

Your default transformation can also be a complex, chained transformation object that controls the size, 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 (requires insert_transformation to be true), this 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
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)
insert_transformation Boolean. Whether to allow users to apply a transformation to the selected asset. When true, only one media asset can be selected at a time and the multiple parameter is ignored. False
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.

This option is relevant only when the insert_transformation parameter is false (or omitted). If both parameters are set as true, the multiple parameter is ignored.

True
z_index Sets the CSS stack order of the Media Library element.

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

None

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 (or will prompt alex to log in, if he is not already), and will enable him to drill down to a selected media asset and apply transformations.

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

3. 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"
}, [...]]}

4. 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 Media Library instance.
  • 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

You can use the show() and hide() methods to open and close the widget in your application. For example:

  • window.ml.show()
  • window.ml.hide()

When calling show(), if the user is not yet logged into Cloudinary (either directly or via SSO), a link prompts the user to log in.

5. 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.

Without this option enabled, your users will need to separately log into Cloudinary when the widget opens, unless they have previously logged in via the Cloudinary console.

Note
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.

6. 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 configuration includes a customized button class and button text that will replace the open-btn HTML element in the CMS page. The widget will enable this user to drill down into his selected media asset to apply transformations. 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',
   insert_transformation: true,
 }, {
     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 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',
  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)) })
       }
     }
  )