Image Effects Creating Custom Image Cropping Interfaces in Android How to Create Simple Yet Effective PHP Overlay Understanding Real-Time Image Recognition How to add a shadow effect to an image with CSS How to crop an image in Flutter with Cloudinary How To Rotate an Image with Java Image Processing with Python Rotating an image with CSS Enhancing User Experience with a Responsive Image Slider Building a Python Image Recognition System Building an Interactive JavaScript Image Manipulation Tool Image Align Centering with HTML and CSS Efficient Image Cropping Techniques with Angular and Cloudinary Ultimate Guide to Photo Gallery on Android A Comprehensive Guide to Adding Text to Images on Android Mastering Background Changes in React Applications Comprehensive Guide on Changing Background on Android Devices Mastering Image Rotation in Java A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

How To Create a Progress Bar For Asset Uploads

create progress bar

Uploading files can be tedious; without proper feedback, users can wonder how long they have to wait until it’s complete. However, a well-designed progress bar can indicate how far along the upload process is, reducing frustration and enhancing the user experience.

In this tutorial, we’ll show you how to leverage a powerful JavaScript SDK and API to create a sleek, modern progress bar that will keep users informed and engaged during asset uploads. So, let’s dive in and learn how to create an elegant progress bar!

In this article:

What Is a Progress Bar?

A progress bar is a graphic component that informs users visually of the progress of a procedure, like an upload or download. Usually, it shows a graphic depicting progress or the proportion of work completed.

When Do You Need to Create a Progress Bar?

When a process requires a significant amount of time and the user wants updates on its status, a progress bar should be created. This is crucial for web apps because users demand responsive and quick interactions.

By clearly stating how long the process will take to finish, a progress bar can help users feel less impatient. It can also help users trust an application by showing them it is actively working and moving forward.

How to Create a Progress Bar Automatically

Now that we know the importance of progress bars let’s look at how we can use Cloudinary to make progress bars for users creating user-generated content.

Prerequisites

To follow along with this tutorial, you should have basic knowledge of HTML, CSS, and JavaScript/jQuery. Additionally, you will need a Cloudinary account. If you don’t already have one, you can create a free account by visiting their website.

Next, you will need to create an upload preset to streamline the process of uploading files from the client. This essential step enables you to define a set of asset upload options centrally instead of specifying them in each upload call.

To create your preset, log in to your Cloudinary account and head to Settings.

Dashboard

Next, head to Upload in your Cloudinary settings and select Enable unsigned uploading:

Enable size upload

This will create an unsigned upload preset that we will be using to upload our images to our Cloudinary cloud:

Upload presets

Now that everything is set up, we can start creating our basic progress bar with HTML.

Creating a Basic Progress Bar with HTML

The first step to creating a basic progress bar is to create a new HTML file and set up the basic structure. We’ll need to include the HTML5 doctype declaration and opening and closing the html, head, and body tags.

<!DOCTYPE html>
<html>
  <head>
    <title>Cloudinary Upload Progress Bar with jQuery</title>
  </head>
  <body>
  </body>
</html>

Next, include the jQuery library and the necessary jQuery file upload libraries. You can do this by adding script tags with the URLs to each library in the head section of your HTML file so they load as the page loads.

<!DOCTYPE html>
<html>
  <head>
    <title>Cloudinary Upload Progress Bar with jQuery</title>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- jQuery UI Widget -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.19.2/js/vendor/jquery.ui.widget.min.js"></script>

    <!-- jQuery Iframe Transport -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.19.2/js/jquery.iframe-transport.min.js"></script>

    <!-- jQuery File Upload -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.19.2/js/jquery.fileupload.min.js"></script>

    <!-- cloudinary-jquery-file-upload -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cloudinary-jquery-file-upload/2.13.0/cloudinary-jquery-file-upload.min.js"></script>
  </head>
  <body>
  </body>
</html>

Next, in the body, we’ll need a form that allows users to select and upload an image to Cloudinary. To do this, add a form element with an input type of "file" and a data-cloudinary-field attribute set to "image_id". Also, add a progress bar element to display the upload progress:

  <body>
    <h1>Upload an Image to Cloudinary with jQuery</h1>
    <form id="uploadForm">
      <input type="file" name="file" data-cloudinary-field="image_id">
      <progress id="progressBar" value="0" max="100"></progress>
    </form>
  </body>

Here is what our form looks like:

Form

Manipulate the Page with JavaScript

Start by creating a script tag right below our form and start by defining our cloudName, apiKey, and uploadPreset:

<script>
      // Set your Cloudinary cloud name and API key
      const cloudName = 'CLOUD_NAME';
      const apiKey = 'API_KEY';

      // Set your Cloudinary upload preset name
      const uploadPreset = 'UPLOAD_PRESET';
</script>

Next, we’ll define an object called uploadOptions that will contain options for our Cloudinary upload. These options include:

  • url: The URL of the Cloudinary upload API endpoint. We’ll set this to https://api.cloudinary.com/v1_1/${cloudName}/image/upload, where ${cloudName} is the name of our Cloudinary cloud.
  • formData: An object that contains additional form data that will be sent with our upload request. We’ll set the api_key and upload_preset fields to our Cloudinary API key and upload preset, respectively.
  • progress: A function that will be called periodically to update the progress graph during the upload process. We’ll calculate the progress percentage and update the value attribute of the progress chart element accordingly.

Here is what our uploadOptions will look like:

      const uploadOptions = {
        // Set the Cloudinary unsigned upload endpoint URL
        url: `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`,
        // Set the Cloudinary API key and upload preset
        formData: {
          api_key: apiKey,
          upload_preset: uploadPreset
        },
        // Set up an upload progress function
        progress: (event, data) => {
          // Calculate the progress percentage
          const progress = Math.round((data.loaded / data.total) * 100);
          // Update the progress bar value
          $('#progressBar').val(progress);
        }
      };

Now that we’ve defined the uploadOptions object, we’re ready to initialize the Cloudinary file uploader. We’ll initialize the Cloudinary file uploader by calling the cloudinary_fileupload method on our file input element. Then, we’ll pass the uploadOptions object we defined in the previous step as an argument to this method:

$('#uploadForm input[type="file"]').cloudinary_fileupload(uploadOptions);

This code will select the file input element inside the uploadForm form element using a jQuery selector and then calls the cloudinary_fileupload method on it, passing in the uploadOptions object we defined earlier.

Now that our basic code is ready, we will add an event handler to handle the cloudinarydone event that is fired when a file upload completes successfully. This event contains information about the uploaded file, such as its public ID, URL, and other metadata.

We’ll use this information to display the uploaded image on our website. Specifically, we’ll create an img element and set its src attribute to the URL of the uploaded image. We’ll then append this element to the body of our HTML document:

$('#uploadForm').bind('cloudinarydone', (event, data) => {
  console.log('Upload success:', data);
  const uploadedAssetUrl = data.result.url;
  const imgElement = $('<img>').attr('src', uploadedAssetUrl);
  $('body').append(imgElement);
});

Using the jQuery bind method, the code will bind a callback function to the cloudinarydone event. This function takes two arguments: event, which is the event object, and data, which is an object containing information about the uploaded file.

Inside the callback function, we first log the data object to the console for debugging. Then, we use the data.result.url to get the URL of the uploaded image stored in the data object.

Finally, we create a new img element using the jQuery $('<img>') syntax, set its src attribute to the uploaded image URL, and append it to the body of our HTML document using the append method. Here is what our final code looks like:

<!DOCTYPE html>
<html>
  <head>
    <title>Cloudinary Upload Progress Bar with jQuery</title>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- jQuery UI Widget -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.19.2/js/vendor/jquery.ui.widget.min.js"></script>

    <!-- jQuery Iframe Transport -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.19.2/js/jquery.iframe-transport.min.js"></script>

    <!-- jQuery File Upload -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.19.2/js/jquery.fileupload.min.js"></script>

    <!-- cloudinary-jquery-file-upload -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cloudinary-jquery-file-upload/2.13.0/cloudinary-jquery-file-upload.min.js"></script>

  </head>
  <body>
    <h1>Upload an Image to Cloudinary with jQuery</h1>
    <form id="uploadForm">
      <input type="file" name="file" data-cloudinary-field="image_id">
      <progress id="progressBar" value="0" max="100"></progress>
    </form>

    <script>
      // Set your Cloudinary cloud name and API key
      const cloudName = 'CLOUD_NAME';
      const apiKey = 'API_KEY';

      // Set your Cloudinary upload preset name
      const uploadPreset = 'UPLOAD_PRESET';

      const uploadOptions = {
        // Set the Cloudinary unsigned upload endpoint URL
        url: `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`,
        // Set the Cloudinary API key and upload preset
        formData: {
          api_key: apiKey,
          upload_preset: uploadPreset,
        },
        // Set up an upload progress function
        progress: (event, data) => {
          // Calculate the progress percentage
          const progress = Math.round((data.loaded / data.total) * 100);
          // Update the progress bar value
          $('#progressBar').val(progress);
        }
      };

      // Initialize the Cloudinary file uploader
      $('#uploadForm input[type="file"]').cloudinary_fileupload(uploadOptions);

      // Handle the file upload success event
      $('#uploadForm').bind('cloudinarydone', (event, data) => {
        console.log('Upload success:', data);
        // Display the uploaded asset on your website
        const uploadedAssetUrl = data.result.url;
        console.log(uploadedAssetUrl);
        const imgElement = $('<img>').attr('src', uploadedAssetUrl);
        $('body').append(imgElement);
      });
    </script>
  </body>
</html>

Now we can simply save our HTML and run our file in our browser:

Upload forms

Next, select a file to upload to the cloud. Here we will be uploading a file named cld-sample.jpg located in the assets folder on our desktop:

Image

Image upload

You can use your upload by heading to the Media Library tab on your Cloudinary account:

Progress bar

Closing The Book

Adding a progress bar for image uploads can significantly improve how users interact with your app. The procedure is simple and easy to follow with Cloudinary’s API and JavaScript SDK. Utilize this feature and many others by signing up for Cloudinary today to enhance your media delivery and administration.

Learn more:

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better implement and optimize progress bars for asset uploads:

  1. Provide contextual feedback with percentage and time estimates
    Enhance user experience by including numerical values or estimated time left along with the progress bar. For example, display “Uploaded 50% (15 seconds left)” alongside the bar. Use libraries like moment.js to calculate time estimates dynamically based on the upload speed. This offers more precise feedback and reduces uncertainty during long uploads.
  2. Utilize adaptive buffering for smoother animations
    Progress bar animations can appear jarring if the upload speed varies drastically. Implement adaptive buffering, where the progress bar smooths out small fluctuations in the upload speed to present a consistent movement. Use request animation frames (requestAnimationFrame) instead of CSS transitions for fine control over bar animations.
  3. Indicate status changes using color cues
    Use color transitions to reflect different states: blue for uploading, green for successful completion, and red for errors. Pair these with subtle icons or status text for accessibility, ensuring visually impaired users can also comprehend the upload status changes.
  4. Add interactive features like cancel or pause buttons
    Make the progress bar interactive by adding options to cancel, pause, or resume uploads. For multi-file uploads, add checkboxes to let users choose which uploads to pause or cancel individually. This control can be crucial for users on limited bandwidth connections.
  5. Handle error states gracefully
    Display specific error messages if uploads fail, such as “Network issue, retrying…” or “File too large, please upload files under 5MB.” Offer automatic retries for network issues using a back-off strategy (e.g., exponential backoff). Implementing these features shows users that your app is resilient and reliable under varying conditions.
  6. Implement multi-file progress management
    For bulk uploads, aggregate the individual progress bars into a global progress indicator. This keeps the interface clean and provides an overall sense of how much is completed. Use libraries like RxJS to track and merge multiple file upload observables into a single aggregate progress metric.
  7. Ensure the progress bar adapts to different screen sizes
    Progress bars should remain effective across various devices, from mobile to desktop. Use responsive units like % and vw (viewport width) instead of fixed pixels, and ensure text or icons scale correctly. This maintains the visual quality and clarity of the progress indicators on smaller screens.
  8. Pre-check for file size and type before upload
    Avoid the frustration of failed uploads by pre-checking file size and type before initiating the upload. Use JavaScript’s FileReader API to validate file properties. Show a warning if the file exceeds predefined limits or if the format isn’t supported, saving time and reducing server load.
  9. Enable background uploads to improve the user flow
    Background uploads allow users to continue interacting with the site while the files upload. Use a notification-style progress bar in the corner of the screen, like YouTube’s background uploader. This non-intrusive progress bar can improve overall engagement and user satisfaction.
  10. Leverage Cloudinary’s upload transformations and optimizations
    For complex uploads, consider using Cloudinary’s additional upload options, such as automatic image optimizations, watermarking, and format conversions. Use transformation parameters to apply image transformations during upload (upload_preset), reducing the need for additional client-side processing.

These advanced strategies can transform a basic progress bar into a highly functional and user-friendly interface component, making the upload process seamless and enjoyable for your users. Implementing these features will not only enhance the visual appeal but also improve the overall usability of your application.

Last updated: Oct 3, 2024