PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How can i remove Specific item from Formdata object array?

 September 06, 2022     ajax, form-data, javascript     No comments   

Issue

i tried to access formData's specific item to remove it from formData Object and get it's name value.

i've tried formdata.delete through console but it remove whole object with undefined returns, but i want to remove single item which can be identified by file.name

here's 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;
    
  }


since i use controller for ajax i can not change formData.append name value any help will be appreciated, thank you.


Solution

The delete function of FormData do indeed work :

let f = new FormData
f.append('test', 'data')
Array.from(f.keys()).forEach((k) => { console.log(k) })
test
f.delete('test')
Array.from(f.keys()).forEach((k) => { console.log(k) })
// nothing printed in the console

But you don't really need that function, use get method to retrieve fileupload[], change it, and use set method to update the FormData object

let f = new FormData

// get fileupload
let val = f.get('fileupload[]')

// do what you want

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



Answered By - Lk77
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing