简体   繁体   中英

how to remove an element from an array contained in a formData ()

I have a code with which I intend to attach an array of files on the "anexos_detalle_reunion" key. In my code, I have executed this line of code 3 times, so it is normal to add an element named "anexos_detalle_reunion[]" to my formData () 3 times. I need to specifically delete the "anexos_detalle_reunion[]" key located in position 1 and keep the others.

在此处输入图片说明

how can I do it?

var FormData=new FormData();
formData.append('anexos_detalle_reunion[]', file, file.name);


fileChange(event:any) {
   let fileList: FileList = event.target.files;
   console.log(fileList);
   if(fileList.length > 0) {
       let file: File = fileList[0];
       console.log(file,file.name);
       this.formData.append('anexos_detalle_reunion[]', file, file.name);
   }
}

Don't build your FormData until you have to upload it to your server. A FormData object is not practical to store data. There are many other Objects in js that can do it way better, for instance a simple Array is all you need in your case.

So in the input's change event, you push the new Files in an Array.
You do the modifications you want from this Array. When it's time to send it to the server, you build your FormData with what remains in the Array:

 const files = []; // a simple Array; inp.onchange = e => { const file = inp.files[0]; files.push(file); // store in the Array makeRemoveButton(file); } btn.onclick = e => { // could be form.onsubmit // here we build the FormData const fd = new FormData(); files.forEach(f => { fd.append('files[]', f, f.name); }); console.log(...fd); // fetch(..., {body: fd, ... }; function makeRemoveButton(file) { const btn = document.createElement('button'); btn.textContent = 'remove ' + file.name; btn.onclick = e => { btn.remove(); files.splice(files.indexOf(file), 1); }; document.body.append(btn); } 
 <input type="file" id="inp"> <button id="btn">send</button><br> 

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