Customizing File Size and Dimensions in Form Submission with Dropzone.js in JavaScript

I am currently experimenting with some sample code for Dropzone.js and am interested in finding a way to include the file size as a form field when submitting:

var KTFormsDropzoneJSDemos = {
    init: function(e) {
        new Dropzone("#kt_dropzonejs_example_1", {
                url: "add/submit/",
                paramName: "file",
                maxFiles: 10,
                maxFilesize: 10,
                addRemoveLinks: !0
            }),
            function() {
                const e = "#kt_dropzonejs_example_3",
                    o = document.querySelector(e);
                var r = o.querySelector(".dropzone-item");
                r.id = "";
                var t = r.parentNode.innerHTML;
                r.parentNode.removeChild(r);
                var l = new Dropzone(e, {
                    url: "add/submit/",
                    parallelUploads: 20,
                    maxFilesize: 0.25, // 1 MB
                    acceptedFiles: ".jpeg,.jpg",
                    previewTemplate: t,
                    previewsContainer: e + " .dropzone-items",
                    clickable: e + " .dropzone-select"
                });
                l.on("addedfile", (function(e) {
                    o.querySelectorAll(".dropzone-item").forEach((e => {
                        e.style.display = ""
                    }))
                })), l.on("totaluploadprogress", (function(e) {
                    o.querySelectorAll(".progress-bar").forEach((o => {
                        o.style.width = e + "%"
                    }))
                })), l.on("sending", (function(e) {
                    o.querySelectorAll(".progress-bar").forEach((e => {
                        e.style.opacity = "1"
                    }))
                })), l.on("complete", (function(e) {
                    const r = o.querySelectorAll(".dz-complete");
                    setTimeout((function() {
                        r.forEach((e => {
                            e.querySelector(".progress-bar").style.opacity = "0", e.querySelector(".progress").style.opacity = "0"
                        }))
                    }), 300)
                }))
            }()
    }
};
KTUtil.onDOMContentLoaded((function() {
    KTFormsDropzoneJSDemos.init()
}));

The Dropzone.js "Tips & Tricks" page provides an example of how to send additional data like file size, height, and width:

Dropzone includes data within the file object that can be accessed during events firing. You can retrieve file.width and file.height if it's an image,

If you need to attach extra data specific to each file being uploaded, you can utilize the sending event:

myDropzone.on("sending", function(file, xhr, formData) {
  // Adds the filesize as POST data along with the file.
  formData.append("filesize", file.size);
});

In the provided example code under the #kt_dropzonejs_example_3, I have the "sending" section mentioned but am unsure how to implement adding the file size as form data similar to the example code. Any guidance on modifying the "sending" function to achieve this would be appreciated.

Answer №1

When handling the sending event based on the example, it is recommended to ensure acceptance of other parameters:

listener.on("sending", (function(file, xhr, formData) {
    container.querySelectorAll(".progress-bar").forEach((element => {
        element.style.opacity = "1"
    }));
    formData.append("filesize", file.size);
})),

In terms of formatting, I suggest a code structure similar to the following:

sampleDropzone.on("sending", (file, xhr, formData) => {
    sampleContainer.querySelectorAll(".progress-bar").forEach(item => item.style.opacity = "1");
    formData.append("filesize", file.size);
});

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

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

Navigating the issue of "Experiencing additional hooks rendered compared to the previous render"

I'm currently in the process of developing a small application where certain elements will be nested within one another. My approach involves segmenting each component into its own file (children), returning a function with two components in each Rend ...

Is there a way to retrieve JSON data from a different domain and incorporate it into my own website?

I am attempting to utilize JSON data from "" and display the data on my website. My goal is to extract the JSON field name "Stats" and retrieve the sub-field name '\"v\"'. You can refer to the documentation provided by purpleair here: h ...

JavaScript's Math.round function does not always produce accurate results

After adding the specified line within the function, the code seems to encounter issues. parseLocalFloatCnt: num = Math.round(num*1.2); Is there a solution available for this problem? Your help is much appreciated. <!DOCTYPE html> <html> < ...

The most basic form of req.body will consistently be devoid of any content

I am currently working on passing basic data from the client to the server using a POST request for testing purposes. However, I am encountering issues with receiving empty or undefined logs on req.body. Server: //jshint esversion:6 const express = requi ...

Is there a way to eliminate the # sign from hash data using jQuery?

Can anyone help me retrieve the hash value from the URL? var hash = window.location.hash; I am looking for a way to remove the "#" sign from the hash. Any suggestions? ...

What is the best way to change the name of a child object within a clone in three.js? (renaming child objects within clones)

I have designed a 3D model using different elements: ParentObject-001.name = 'ParentObject-001'; ChildObjectA-001.name = 'ChildObjectA-001'; ChildObjectB-001.name = 'ChildObjectB-001'; Then, I combined them with: ParentObject ...

When a specific function is called, the DayPickerRangeController in the airbnb/react-dates library will update the

Is it possible to dynamically set the visible month in DayPickerRangeController after the component has been rendered? I have a 'handleMonthChange' function that I want to use to change the visible month, but setting 'initialVisible' mo ...

Transitioning my website to incorporate Angular JS

Recently, I have been exploring AngularJS and I am quite impressed with its features. I am currently developing a website using traditional methods (php, html, css, mysql, some jQuery) and I am considering transitioning to Angular. The reason for this chan ...

What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question: async foo() : Promise<Object> { if(...) throw new Error } I'm wondering how I should go about testing whether the error is thrown. This is my current approach: it("checking for thrown error", asy ...

Using Javascript to Highlight a Single Row in a Table

Greetings esteemed members of the skilled community at StackOverflow, I must humbly ask for your expertise in solving a dilemma that I am currently facing. The situation is as follows: I have a table generated from an SQL query, and it is crucial for the ...

Unexpected behavior of TypeScript optional object key functionality

I am facing an issue with an object that has conditional keys. For example: const headers: RequestHeaders = {}; if (...) { headers.foo = 'foo'; } if (...) { headers.bar = 'bar'; } As a newcomer to TS, I initially thought this wo ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Is there a way to confirm if one field value is greater than another using the Ajv JSON schema validator?

Is it feasible to receive a validation error using ajv when minPrice exceeds maxPrice? What is the recommended method of achieving this, ideally adhering to the JSON schema standard? ...

Developing JSON with the use of jQuery

My latest project involves creating an application that converts HTML tables to JSON format. The code is functioning properly, but I've encountered an issue when the td or th elements contain inner components like span or other child elements. While I ...

Placing a moveable object in a designated spot for dropping at the desired location

I've been attempting to clone and drop a draggable object at the exact position within a droppable area where the drop event takes place. While I have come across examples online that demonstrate appending draggables to droppables, they all tend to re ...

Trouble toggling Reactstrap navbar in my TypeScript project using NextJS

I recently integrated Reactstrap into my NextJS TypeScript project and encountered an issue with the Navbar component. Despite following the example from the Reactstrap documentation, the mobile toggle menu does not open when clicked. Additionally, none of ...

When properties remain unchanged, they do not hold the same value in a Firestore-triggered Cloud Function

Within my Firestore database, there is a collection named events consisting of documents with attributes such as begin, end, and title. The function in question is triggered when any changes occur within a document. The begin and end fields are both categ ...

Utilizing a Single Variable Across Multiple Middlewares in nodeJS

I encountered an issue where I am attempting to utilize one variable across two middlewares, but it displays an error stating that the variable is not defined. Here is an example of my situation: //1st middleware app.use((req, res, next) =>{ cont ...

Updating the parent's data by modifying data in the child component in VueJS

When I use multiple components together for reusability, the main component performs an AJAX call to retrieve data. This data is then passed down through different components in a chain of events. <input-clone endpoint="/api/website/{{ $website->id ...