Sending a request for the second time may result in data duplication

To upload a file to the server, I use the following code snippet:

var fd = new FormData();
fd.append('folder', 'html');
fd.append('permission', 0);
fd.append("file", file, file.name);

After selecting the file from an input field, my request is as follows:

$.ajax({
                     type: "POST",
                      url: getURI("fileupload"),
                      success: function (data) {
                          reader.onload = function (e) {
                              callback(data.body.url, {
                                  alt: ''
                              });
                          };
                          reader.readAsDataURL(file);
                      },
                      error: function (error) {
                          // handle error
                      },
                      async: true,
                      data: fd,
                      cache: false,
                      contentType: false,
                      processData: false,
                      timeout: 60000
                  });

1) Uploading the initial file works fine. 2) When trying to upload a second file, it does upload successfully, but there seems to be an issue with the FormData - when attempting to send multiple files, only the last one gets sent while the others are still being attempted.

Is there a way to remove previous FormData entries?

Answer №1

$.ajax({
    type: "POST",
    url: getURI("fileupload"),
    success: function (data) {
        reader.onload = function (e) {
            callback(data.body.url, {
                alt: ''
            });
        };
        reader.readAsDataURL(file);

        //
        // Make sure to clear the file input at this point
        //
    },
    error: function (error) {
        // handle error
    },
    async: true,
    data: fd,
    cache: false,
    contentType: false,
    processData: false,
    timeout: 60000
});

In the success callback, it is important to manually clear your file input. For more details, refer to this resource

After that, initialize a new FormData instance named fd:

fd = new FormData();

For further information on clearing FormData objects, visit this link

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

Developing an ASP application using the MVP pattern to return JSON data can be transformed into a S

I’m looking to incorporate the following code into a sails js Controller public JsonResult GetEvents() { //Using MyDatabaseEntities as our entity datacontext (refer to Step 4) using (MyDatabaseEntities dc = new MyDatabaseEntities()) { ...

What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem. To access the code, click here: https://stackblitz.com/edit/angular-ivy-87 ...

Tips on adding background images to your chart's background

Is there a way to set an image as the background in Lightning Chart using chartXY.setChartBackground? ...

AngularJS variable assignment with HTTP GET operation

The angular filter I have set up is functioning perfectly: categorieFilter = angular.module("categorieFilter", []) categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){ $scope.search = ""; $scope.products = []; $ ...

When I try to upload an image onto my website, the layout of my text gets disrupted

There seems to be quite a gap between the welcoming message and the main body text. Significant spacing noticed between Title and body ...

When testing my jQuery locally, it runs smoothly. However, upon uploading it to my website, I encounter some issues where it

After successfully running my webpage on localhost, I encountered an issue when uploading it to my website. Only a portion of the code seems to be executing properly. I have included the following jquery function in my script and there are no reported err ...

The user type is not yet loaded from Firestore when the view is rendered

I am currently in the process of developing an Ionic - Angular application that allows hospital patients to submit requests to nursing staff, who can then view the assigned requests based on the patient's room. Nurses have access to all requests, whil ...

Exploring the implementation of useMediaQuery within a class component

Utilizing functions as components allows you to harness the power of the useMediaQuery hook from material-ui. However, there seems to be a lack of clear guidance on how to incorporate this hook within a class-based component. After conducting some researc ...

The MUI Autocomplete filterOptions is not effectively filtering out all options as expected

Hey there! I'm facing an unusual situation with my Autocomplete feature, which has been heavily customized to meet certain restrictions and requirements. The issue I am encountering is related to filtering. Despite successfully filtering the results ...

Transferring data from a stream in NodeJS to FrontEnd using ReactJS

How are you doing? I'm trying to figure out how to send a large data request from PostgreSQL to the FrontEnd in JSON format. Can anyone help with an example of how this can be achieved? Thank you. Here is my code: const express = require('expr ...

Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart. I want to utilize this value to update another value in the template that is not part of the component. Is it achievable? Bel ...

Developing a matrix arithmetic parser using JavaScript

Currently, I am in the process of developing a program that can solve matrix equations. My main focus right now is on making sure the parser functions correctly. However, I am feeling lost and unsure of where to begin. In my program, I utilize an array of ...

Chrome is throwing a syntax error with an unexpected token in jQuery replaceWith

jQuery('div#top').replaceWith('<div id="top"> </div>') When I try to replace the entire content of the top div using jQuery, Chrome gives me an error: "Uncaught SyntaxError: Unexpected token" on the first line. I'm no ...

The magic of data binding in AngularJS's ng-repeat

Is it possible to dynamically call an attribute of a data-binded object based on the ng-repeat object? I have set up a simple example, but I'm not sure if it can be solved this way. Can anyone help with this? The goal is for the input to receive the ...

Exploring the orderBy feature in the react-firebase-hooks library with NextJS

Recently, I've been utilizing the React Firebase Hooks package from this GitHub repository. The code snippet below has been functioning smoothly for me. const [posts, loading, error] = useCollection( firebase .firestore() .collection(& ...

moment.js is unable to extract the time information from a timestamp

I'm having trouble converting a timestamp using moment.js from a json data set. When I try to use moment.format('MMMM Do YYYY, H:mm:ss'), the output is showing something like May 25th 2361, 0:00:00 for the timestamp 12351223423. This seems t ...

JavaScript- Tabbed Navigation with Lists as the Content

Currently, I am facing a frustrating issue in finding a suitable solution. My website uses tabs that utilize the UL, LI system, similar to most tab systems found in tutorials. The problem arises because the javascript on my site interferes with using the ...

Transform URLs to end with .jpg using NextJS

My API has a specific endpoint called /api/thumbnail that currently returns a JPEG image. However, I would like the endpoint to also accept .jpg, so it can be accessed as /api/thumbnail.jpg. Would I be able to achieve this using only pure NextJS code, or ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...

JavaScript: create a collision detection algorithm to find pairs of objects in an object, not an array

I'm in the process of developing a Javascript game and I'm facing the challenge of implementing collision detection. Each element rendered in the game has its own unique ID and is stored in an object. I opted for using an object as a container i ...