javascript – How to remove a field already added to a 'FormData'?

Question:

The following code inserts files from a file field into a FormData :

var filedata = event.target; // FileList object
var i = 0, len = filedata.files.length, file;

for (; i < len; i++) {
    file = filedata.files[i];
    // ...

    // Aqui adiciono o campo ao FormData
    formData.append('img_upload_'+(countFiles++), file);
}

Question

Is it possible to remove at any given time, a file/field previously added to FormData , or do I have to create a new instance, and tell the user to add all the files again?

The above method is executed every time there is a modification ( onchange event) in an input field of type file . At the end, formData will be sent via AJAX.

Answer:

FormData only has an append method. However, in this scenario it would be better not to populate it on onchange . If necessary, you can maintain an array with File objects, and the array can be manipulated when needed. Leave to create/populate the FormData only at the end, right before the AJAX request.

Scroll to Top