Skip to content Skip to sidebar Skip to footer

How Do I Send An Array Of Files Using Xhr2 And Formdata? (java + Spring)

I'm using to upload a list of files. This works fine as is, but I want the ability to remove individual files before upload, so I'm storing the

Solution 1:

In order for Spring to map items in a request to a list, you need to provide the same name (in the FormData.append calls) for each item when appending to the form data. This allows Spring to effectively see the request as name=value1&name=value2&name=value3 (but obviously in the form of form data). When Spring sees the same key ("name") multiple times, it can map the values into a collection. Going with your example, the name "files" is needed because your DocumentsBean has named it that way. That means your JavaScript code should change to be something like this:

function buildForm(form) {
    var files, formData, i, j, xhr;

    files = document.getElementById('attachFiles').files;
    formData = new FormData();

    formData.append('submittedFormAction', "attachDocumentSave");
    for (i = 0, j = files.length; i < j; i++) {
        formData.append('files', files[i]);
    }
    formData.append('testString', "foobar");

    xhr = new XMLHttpRequest();
    xhr.open('POST', form.action, true);
    xhr.send(formData);

    return false;
}

Post a Comment for "How Do I Send An Array Of Files Using Xhr2 And Formdata? (java + Spring)"