Incorporating a progress bar into the file upload feature

Looking to incorporate a minimalist progress bar using jQuery into this HTML. Any suggestions on the simplest approach? Just need a percentage value and a progress bar.

<!DOCTYPE html>
<html>
<body>

<form action="basic.php" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="file" id="file">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Answer №1

Recently, I encountered a project where I needed to achieve the same goal. After exploring various plugins, I came across the dmUploader plugin, which proved to be extremely useful. This plugin allows you to upload images through drag and drop or using the input tag. You can find the plugin HERE.

I have implemented a functional example on CODEPEN, which I believe is the most effective way to learn how to utilize this plugin. The jQuery code from lines 1 to 290 in the example mainly consists of the plugin itself. Since the plugin does not have a CDN link, I had to include it in the code. Let's review the code snippets:

HTML

<div class="SciSecPic">
    <i class="fa fa-fw fa-picture-o"></i>
    <label>
        <span>Click to browse your picture</span>
        <input type="file" title='Click to add Files' style="display:none;">
    </label>

    <div class="progress" style=" display:none;">
        <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
  0%
        </div>
    </div>
</div>

In this example, you need a container div named SciSecPic, a label containing span and hidden input tags. The input tag is hidden, and the span tag serves as the button. Additionally, you can include a progress bar (Bootstrap progress bar in this case) within a div with the class progress, which is only displayed while uploading.

No specific CSS settings are required for this, so I will skip that part and direct you to the functional example for reference.

jQuery - Implementing dmUploader

var readPic;

$(".SciSecPic").each(function () {
    var self = $(this);
    self.dmUploader({
        //url: "/Something/ImageSaver",
        url: "http://posttestserver.com/post.php?dir=ali",
        dataType: "json",
        allowedTypes: "image/*",
        //extraData: {
            //Name: self.data("name"),
            //Id: ~~self.data("id")
        //},
        onInit: function () {

        },
        onNewFile: function (id, file) {

            // showing progressbar
            $(this).find(".progress").show(200);

            /* preparing image for preview */
            if (typeof FileReader !== "undefined") {

                var reader = new FileReader();
                reader.onload = function (e) {
                    readPic = e.target.result;
                }

                reader.readAsDataURL(file);
            };

        },
        onUploadProgress: function (id, percent) {
            $(this).find(".progress-bar").width(percent + "%").attr("aria-valuenow", percent).text(percent + "%");
        },
        onComplete: function () {

            var thisEl = $(this);

            addPic(thisEl, readPic);

            // to fadeout and reset the progress bar at the end
            setTimeout(function () {
                thisEl.find(".progress").hide(200, function () {
                    thisEl.find(".progress-bar").width("0%").attr("aria-valuenow", 0).text("0%");
                })
            }, 300);
        }
    });
});

The variable readPic stores the dataURL of the image to be displayed after uploading completes. You need to update the url to point to the PHP file or controller if you are using MVC. Extra data can be included using the extraData method. Various callback functions are available with dmUploader, such as onUploadProgress for displaying upload progress, onNewFile for preparing the image for preview, and onComplete for post-upload actions. In my case, I utilized the addPic function to display the uploaded picture above the input box.

To keep this response concise, I won't delve into the addPic function here. It is straightforward to comprehend. That covers the basics of using dmUploader effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include @Html.TextAreaFor with a button click action either through jQuery or by using AJX.ActionLink

I am working on an edit form that includes @Html.TextAreaFor controls. I would like to add a 'Add New' link that will insert a new @Html.TextAreaFor control at the end of the current display. Should I use a @Html.TextArea control instead? If so, ...

What causes objects to intersect in A-Frame even when they are seemingly distanced from each other?

My charts appear in front of a globe object in A-Frame, but when I move the camera in the scene, the order of objects changes causing the charts to overlap and become invisible. I'm unsure of the cause and how to fix it. Here are some screenshots of t ...

Access to an Express route in Node JS can only be granted upon clicking a button

Is it feasible to create an express route that can only be accessed once a button is clicked? I want to prevent users from entering the route directly in the URL bar, and instead require them to click a specific button first. I'm curious if this can b ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

Is it possible to leverage React/Next.js for dynamically adding HTML content based on element IDs when integrating with Netlify forms?

Sorry if this question has already been addressed somewhere. I've spent hours searching and troubleshooting without success. I'm still in the process of learning React, as it's a new concept to me. I just need to implement it for a contact ...

In Firefox, the HTML label fails to activate the corresponding input field when the mouse is moved while clicking

If you click on the label in the example below, it will change the state of the input. document.querySelector("label").addEventListener("click", function() { console.log("clicked label"); }); label { -webkit-user-select: none; -moz-user-select: no ...

The toast added to the DOM is not displaying when using the show() function

I'm experimenting with utilizing Bootstrap 5's toast component to exhibit response messages following a jquery Ajax call. For the successful part, I conclude with this code snippet: itsToastTime(response.status, response.message) let toast = $( ...

When trying to access the page via file://, the cookies are not functioning properly

My HTML code is functioning properly in Firefox and even on the W3Schools website when tested using their editor in Chrome. However, when I run my code in Chrome from Notepad++, it doesn't seem to work. It appears that the body onload event is not tri ...

Angular 14 - Issue with passing values through props - Error: Uncaught (in promise): InvalidCharacterError occurs when attempting to set attribute with 'setAttribute' method

I am a beginner with Angular and encountering an issue when trying to pass props from a parent component to a child component. The specific error I am facing is related to an invalid attribute name while using Angular version 14.2.5. core.mjs:7635 ERROR ...

What is the best way to configure Winston with Webpack?

I'm working on an electron application that utilizes node.js and I want to integrate the Winston logging library. After adding Winston to my package.json file, I encountered warnings from the colors.js dependency when running the webpack build command ...

To activate a function, simply click anywhere on the body: instruction

One of my latest projects involved creating a directive that allows users to click on a word and edit it in a text box. Once edited, clicking anywhere on the body should return the word back to its updated form. html <div markdown>bineesh</div& ...

What is the process for creating a parent container in which clicking anywhere inside will cause a child container (built with jQuery UI draggable) to immediately move to that location?

This is a rundown of tasks that I am struggling to code more effectively: When the bar is clicked anywhere, I want the black dot button to instantly move there and automatically update the displayed percentage below it. Additionally, when I drag the butt ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Which specific divs should I assign an ID to within the class?

Is there a way to apply the gray box style to specific divs instead of all of them? Should I include an id somewhere in the code? <!DOCTYPE html> <html> <head> <style> div { width: 320px; padding: 10px; border: 5px soli ...

Malfunctioning carousel

I've been attempting to set up a carousel, but it's not functioning properly. I'm unsure of where the issue lies. The navbar section is working fine, but the carousel isn't appearing at all. Should the carousel be placed above the navba ...

Can the Android Browser Display Seamless IFRAMES?

Did you know that HTML5 offers support for a seamless IFRAME? This feature allows you to easily include headers and footers in your HTML code. However, when I tested this on the Android (2.2) browser, which is supposed to be HTML5-based, it didn't wor ...

When utilizing useMachine in TypeScript, an error is thrown regarding incompatible types

While attempting to build my first example for a xstate finite machine by following the example on github.com/carloslfu/use-machine, I encountered a TypeScript error that halted my progress: Argument of type '{ actions: { sideEffect: () => void; } ...

Is it possible to incorporate jQuery into an AngularJS project?

When it comes to testing, AngularJS is a framework that supports test-driven development. However, jQuery does not follow this approach. Is it acceptable to use jQuery within Angular directives or anywhere in AngularJS for manipulating the DOM? This dilemm ...

Tips for concealing group heading when no child elements match user search

We have implemented an Angular search feature for subjects. However, we want to hide the subjects category if the search keyword does not match any subjects in the respective group. For example, we should hide the "Sports & Arts" category when the user ...