简体   繁体   中英

How can i remove Specific item from Formdata object array?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM