[英]how to remove an element from an array contained in a formData ()
我有一个代码,打算在“ anexos_detalle_reunion”键上附加一个文件数组。 在我的代码中,我已经执行了这行代码3次,因此向我的formData()中添加3次名为“ anexos_detalle_reunion []”的元素是正常的。 我需要专门删除位置1中的“ anexos_detalle_reunion []”键,并保留其他键。
我该怎么做?
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);
}
}
在必须将其上传到服务器之前,不要构建FormData。 FormData对象存储数据并不实用。 js中还有许多其他对象可以做得更好,例如,您需要的只是一个简单的数组。
因此,在输入的change事件中,将新文件推送到数组中。
您可以从该数组进行所需的修改。 当需要将其发送到服务器时,可以使用Array中剩余的内容来构建FormData:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.