简体   繁体   English

如何从 Formdata object 数组中删除特定项目?

[英]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.我试图访问 formData 的特定项目以将其从 formData Object 中删除并获取它的名称值。

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我已经通过控制台尝试了 formdata.delete,但它删除了带有未定义返回的整个 object,但我想删除可以通过 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.由于我将 controller 用于 ajax,因此我无法更改 formData.append 名称值,我们将不胜感激,谢谢。

The delete function of FormData do indeed work: FormData 的删除 function 确实有效:

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但是你真的不需要那个 function,使用get方法检索fileupload[] ,更改它,然后使用set方法更新 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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