Eliminating duplicate uploads in JavaScript

Within my HTML code, there is a section where users can drag and drop files for upload. Inside this area, there is also a "browse for files" button that triggers a hidden file input if users prefer the traditional upload method. Everything functions correctly except for one issue: when a user drags and drops multiple files (more than one), each file gets uploaded twice (for example, 3 dropped files result in 6 uploads). Interestingly, this duplication does not occur when using the browse button for file selection. After some debugging, I have determined that the problem lies within my ondrop function, which I have provided below. If needed, I can share more code snippets to help identify the source of the issue.

Update: Upon logging the droppedfile variable before and after the for loop, I observed an unexpected behavior. When two files were dropped, the variable contained 2 fileLists, each containing both files (resulting in 4 uploads). This led me to question how my for loop was affecting the variable.

 dropzone.ondrop = function(e){
    e.preventDefault();
    this.className = 'dropzone';
    var droppedfile = e.target.files || e.dataTransfer.files;
    for (i=0; i < droppedfile.length; i++) {
       if(droppedfile[i].type != "text/plain" && droppedfile[i].type != "application/pdf" && droppedfile[i].type != "application/msword"){
           alert(droppedfile[i].type + " file types are not allowed.");
       }else{
           uploadButton.innerHTML = 'Uploading...';
           //calls a function that assigns the file to a new formdata obj and sends via ajax                      
           upload(droppedfile);

       }
    }
}

Answer №1

The issue arises because both files are being uploaded every time the for loop runs. Instead of

upload(droppedfile);

try

upload(droppedfile[i]);

Another approach is to validate all files before uploading

var valid=true;
for (i=0; i < droppedfile.length; i++) {
   if(droppedfile[i].type != "text/plain" && droppedfile[i].type != "application/pdf" && droppedfile[i].type != "application/msword"){
       alert(droppedfile[i].type + " file types are not allowed.");
       valid=false;
   }
}
if(valid) {
   uploadButton.innerHTML = 'Uploading...';                     
   upload(droppedfile);
}

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

Issue with javascript code not functioning post axios request

When working on my project, I utilize axios for handling Ajax requests. I crafted a script that attaches a listener to all links and then leverages Axios to make the Ajax request. Following the Ajax request, I aim to execute some post-processing steps. Aft ...

ajax: ensure utf-8 encoding is applied

I am facing an issue with my webpage that is saved in UTF-8 encoding. In the head section of the HTML document, I have defined it as follows: <meta charset="utf-8" /> Within an external JavaScript file, there is a function called ajax_db() which ma ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

Options for HTML technologies in an application designed for managing enterprise metadata

Challenge We are facing the decision of determining which technologies to adopt as we transition from a rich client Silverlight application to an HTML-based client that can accommodate a metadata driven approach. Situation Our enterprise has been using ...

Selecting items with checkboxes in a Bootstrap dropdown menu

As I work on customizing a bootstrap dropdown with checkboxes, my goal is to have the label name written on the input dropdown in between ';' whenever a checkbox from the dropdown is selected. This will create a similar result as shown in the upl ...

Updating an href based on the presence of a variable in the URL

I've implemented an AMP layout where a unique code is added to the URL based on the traffic source. This code is used to update phone numbers displayed on the site. For instance, if you visit https://example.com/text?bid=1234 I created a script that ...

Experience the convenience of Visual Studio Code's auto-completion feature for HTML tags even when working within an

My HTML file has a babel script embedded within it. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React tutorial</title> <script src="https://unpkg.com/react@16/umd/react.development.js" ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

JavaScript's inability to properly export CSV data containing the "#" character has been causing issues

When exporting JSON data to CSV format and downloading it using JavaScript, everything typically works fine. However, there is a problem if the data contains the hash sign #. The function fails to export all the data in that case, for example: This is my ...

Converting a JSON object with numerical keys back to its original form

Recently diving into JavaScript programming, I find myself struggling with reversing the keys of a single JSON object. Here is the specific object that I'm attempting to reverse: {70: "a", 276: "b ", 277: "c ", 688: "d", 841: "e", 842: "f", 843: ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...

Utilize Function to Gain Access to React Context

As I work on developing a package that enhances the responsiveness of my React widget, I have encountered an issue. The responsiveness now relies not on the viewport width, but rather on the width of the widget container element. Presently, I am wrapping ...

Ajax login feature not redirecting to login popup after successful login

When attempting to open a popup by clicking on the login window, a pop-up appears with a URL requesting username and password along with Google sign-in. However, when a user tries to log in using Google sign-in through the pop-up, it fails to redirect to ...

Retrieve all items pertaining to a specific week in the calendar

I'm trying to obtain a list of week ranges for all data in my MongoDB. When a week range is clicked, only the records for that specific week range should be displayed. By clicking on the week range, the ID of the week (let's say 42, representing ...

Transferring a method through two layers of hierarchy

I'm currently working on a fun little game project, but I've hit a roadblock when it comes to passing a particular method down to its grandchildren components. Despite finding similar discussions on this topic, none seem to address my specific qu ...

Storing Data in Web Browsers: HTML5's localStorage, Cookies, and

After browsing through numerous search results on SO, it seems that HTML5's localStorage feature is particularly advantageous compared to Cookies for storing large amounts of data that doesn't need to be sent to the server. (Local Storage vs Cook ...

JQuery not updating the visibility of elements with the "d-none" class when switching to another tab

Currently, I am attempting to conceal a specific section of my webpage in order to display a "loading" spinner. I achieve this by employing jQuery to add the class "d-none" and remove the class "d-none" from the desired element that needs to be hidden or s ...

Comparing WebSockets and XHR for transmitting data

Looking to optimize the architecture of a web application using Node.js, the goal is to efficiently send medium-sized files to the client from a gallery. Each gallery item should be delivered to the user as quickly as possible in binary form. The file size ...

Is there a way to set the menu to automatically open when the page loads?

Looking for some help with a slide out menu that I want to be always open and cannot be closed. I tried changing the open=true setting to open=false but it didn't work as expected. Here's the code snippet below. I aim to remove the open and close ...