Is there a way to eliminate a particular item from a Formdata object array?

Looking to access a specific item in formData to remove it from the Object and retrieve its name value.

I attempted formdata.delete through the console, but it removed the entire object with undefined returns. What I want is to remove a single item that can be identified by file.name

Here is my code:


<form id="submitform">
    =<input type="text" id="submitReviewWriter" name="reviews"
                                    class="form-control" placeholder="Comment">
<div class="text-center">
     <input type='file' id='fileupload' name="fileupload[]" multiple />
        <div id="uploadedList" class='uploadedList'></div>
            <button id="submitReview" type="submit"class="btn btn-main text-center">submit Comment</button>
    </div>
</form>

<script>
var formData = new FormData();
         var filelist;
         var i = 0;
        
            $("#fileupload").on("change",function handleImgFileSelect(e) {
                filelist = document.getElementById("fileupload").files || [];
                
                for(var i = 0 ; i < filelist.length; i ++){
                    
                    console.log('foundfile' + i + '=' + filelist[i].name);
                    
                    formData.append("fileupload[]",filelist[i]);
                    
                }
                
                var ufiles = e.target.files;
                var filesArr = Array.prototype.slice.call(ufiles);
         
                var reg = /(.*?)\/(jpg|jpeg|png|bmp)$/;
                
                var sel_file;
                var fString = "";
         


                //generate thumbnails dynamically for user
                filesArr.forEach(function(f) {
                    if (!f.type.match(reg)) {
                        alert("not image file extension");
                        document.getElementById("fileupload").value = "";
                        return;
                    }
                    var reader = new FileReader();
                    
                    reader.readAsDataURL(f);
                    
                    reader.onload = function(e) {
                        $(".uploadedList").append('<img src="'+ e.target.result+'" width = "50px" height = "50px" class = "uploadedimg">');
                  }
                }); 
                
            });


//ajax

                         $.ajax({
                                    url: '<%=request.getContextPath()%>/uploadAjax',
                                    data : formData,
                                    processData: false,
                                    contentType: false,
                                    enctype: 'multipart/form-data',
                                    type: 'POST',
                                    success: function(result){
                                        
                                        console.log(result);
                                     }               
                             });


</script>


//Ajaxcontroller

    @ResponseBody
    @RequestMapping(value = "/uploadAjax", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
    public ResponseEntity<String> uploadAjax(@RequestParam("fileupload[]") List<MultipartFile> files) throws Exception {
        
        for(MultipartFile file : files) {
        
            UploadFileUtils.uploadFile(fileuploadPath, file.getOriginalFilename(), file.getBytes());
            logger.info(file.getOriginalFilename());
        }
        
        return new ResponseEntity<>(HttpStatus.CREATED);
                
    }
   public static String uploadFile(String uploadPath, 
                              String originalName, 
                              byte[] fileData)throws Exception{
    
    UUID uid = UUID.randomUUID();
    
    String savedName = uid.toString() +"_"+originalName;
    
    String savedPath = calcPath(uploadPath);
    
    File target = new File(uploadPath +savedPath,savedName);
    
    FileCopyUtils.copy(fileData, target);
    
    String formatName = originalName.substring(originalName.lastIndexOf(".")+1);
    
    String uploadedFileName = null;
    
    if(MediaUtils.getMediaType(formatName) != null){
      uploadedFileName = makeThumbnail(uploadPath, savedPath, savedName);
    }else{
      uploadedFileName = makeIcon(uploadPath, savedPath, savedName);
    }
    
    return uploadedFileName;
    
  }


Due to using the controller for ajax, I am unable to change the formData.append name value. Any assistance would be greatly appreciated. Thank you.

Answer №1

The delete functionality within the FormData object does in fact work as demonstrated:

let form = new FormData
form.append('test', 'data')
Array.from(form.keys()).forEach((key) => { console.log(key) })
test
form.delete('test')
Array.from(form.keys()).forEach((key) => { console.log(key) })
// nothing will be printed to the console

However, the use of the delete method may not always be necessary. Instead, you can utilize the get method to retrieve values from fileupload[], modify them, and then update the FormData object using the set method.

let form = new FormData

// get the value of fileupload
let value = form.get('fileupload[]')

// perform desired operations on the value

// set the value back
form.set('fileupload[]', value)

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

Methods for accessing data from individual files on the node server when uploading multiple files using multer through AJAX

After selecting 3 files for upload, I want to also retrieve their attributes like filename and path on the server side using nodejs. How can this be achieved? https://i.stack.imgur.com/Vzg00.png I have tried accessing it in req.body and req.query, but I a ...

retrieving the site's favicon icon

Currently, I am attempting to extract favicons from website URLs using the HtmlAgilityPack library. While I have been successful in retrieving some favicons, there are still some that remain elusive. I suspect that the inconsistency lies in the implementat ...

Having trouble accessing the div element inserted by the Angular application

I've encountered an issue while trying to access a div that is injected into the DOM by an Angular app on the page. Below is the script I have placed at the end of the HTML page: $(document).ready(function () { var targetNode = document.querySelect ...

Using Firebase onDisconnect with React Native

I am currently working on a React Native app and I am facing an issue where I need to update the user status to 'offline' in Firebase when the user closes the app. Here is what I have tried: import React, { Component } from 'react' ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

Retrieve the current domain name (server name) within a Shiny application

I am managing 3 servers - alpha, beta, and gamma. The goal is to deploy my Shiny code from the alpha server to the gamma server. However, I encounter a challenge. In my ui.R file, I reference another site called start using href = 'https://alpha.com/ ...

Does adding the async attribute to a script impact the timing of the onload event?

I am facing an issue with a webpage that contains a script tag in the HEAD section: <script src="somescript.js" type="text/javascript" async></script> Since it has the async attribute, this script loads asynchronously, allowing the browser to ...

Is it possible to modify a dependency import based on the specific request?

How can I switch between test mode and live mode using Stripe's SDK based on a query parameter in my internal form service for collecting payments? For example, consider this route: router.post("/:formId", function(req, res, next) { let isTest ...

Having trouble with testing an Angular directive?

This is a snippet from my directive spec file for Angular 6. import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { TestBed, ComponentFixture, async } from '@angular/core/testing'; import { By } from ' ...

The perplexing quandary of validating email uniqueness in AngularJS

My form in Angular needs to be able to detect duplicate user emails. The code I'm concerned about can be found here: http://plnkr.co/edit/XQeFHJTsgZONbsrxnvcI This code includes the following directives: ngFocus: tracks whether an input is on focu ...

Secure your messages with PHP encryption and decrypt them with JavaScript

I am looking for a way to encrypt a message using PHP and then decrypt it using JavaScript on the client side. I tried using Blowfish with mcrypt, but encountered an issue where PHP was outputting non-alphanumeric characters while JavaScript was only displ ...

Upon page refresh, products are automatically added to the cart

While developing a shopping cart code, I encountered an issue where refreshing the page automatically added a product to my cart without any action from me. For instance, my website displays three products: Apple, Banana, Orange. When I click on Apple, it ...

I must design a unique layout for my website

I am creating a webpage with various shapes and elements. However, I am facing a challenge with creating a shape that is commonly used. In platforms like Khan Academy, there is simulated programming where shapes can be easily created with a simple command ...

Using Jquery and Ajax to Process JSON Data

Currently experimenting with the API. This API generates random user data in JSON format, but I'm facing difficulties in parsing the response. Every time I try, I end up receiving undefined objects. Below is the code snippet that I am using: <sc ...

Dynamic Backbone.js Models

In the process of developing a Web Application using Backbone.js. I have a web service providing information on the required fields for my model. Therefore, creating a static model is not possible. How can I create a dynamic model for my application that ...

Error with Socket.io server in React client and Javascript server communication

I've been immersed in a React tutorial where I'm constructing a PVP chess game. The mechanics of the game are set, and my focus is now on implementing websockets (socket.io) to enable player interaction and move communication. However, as I dive ...

Separating an Array Subset in JavaScript/jQuery

I need to filter a specific part of a javascript array containing objects by a particular condition, such as: object.property == 2 Instead of manually building a new array with the matching items, I am curious if there is a shortcut for this process. ...

How can I retrieve an array from an object containing both a property and an array in TypeScript?

One of my objects always consists of a property and an array. When I use the console.log(obj) method to print it out, it looks like the following example: ProjectName: MyTest1 [0] { foo: 1, bar: 2} [1] { foo: 3, bar: 4} [2] { foo: 5, bar: 6} Alternat ...

Showing the default option at all times with React Material-UI Autocomplete

For my address search/verification form in React, I'm utilizing the Material-UI Autocomplete component and I want to always display a default option regardless of the search results. In Angular, I achieved this by using [displayWith] along with a fun ...

Tips for managing a JSON response

Currently, I am facing a dilemma while using Python websockets to handle JSON objects. I have a working example with JavaScript that utilizes parseJSON as shown below: socket = io.connect("__socket address__"); socket.on("connect", function() {socket.emit ...