I am writing a web utility that submits a file and some form fields via Ajax. There's a part of my form that is dynamic, as in it can have multiple rows for the same value. The user can add as many rows as they like. The form also takes in a file.
The HTML ends up being something to the effect of:
<form id="main-form">
<input name="inputField[0]" type="text"></input>
<input name="inputField[1]" type="text"></input>
<input name="inputField[2]" type="text"></input>
<input name="inputField[3]" type="text"></input>
....
<input name="inputField[i]" type="text"></input>
<input type = "file" name="file></input>
</form>
Upon the submit button being clicked, the following Ajax is called:
var mainForm = $("#main-form");
$.ajax({
url: '/',
type: 'POST',
success: successHandler,
data: mainForm.serialize(),
complete: checkError,
cache: false,
processData: false
});
Here's the issue. I'm now stuck in a sort of catch-22. The recommended way to pass files through Ajax is using the FormData object. The problem is that I cannot get FormData to cooperate with my arrays. When the NodeJS server receives the Ajax submission as FormData object, it doesn't play nicely with the form arrays. It treats them as individual input fields like (console.log(request.body)):
{ normalField: 'normalResult',
'inputField[0]': 'test0',
'inputField[1]': 'test1',
'inputField[2]': 'test2',
'inputField[3]': 'test3',
}
where as the .serialize() method gives me a nice array like:
{ normalField: 'normalResult',
inputField:
[ 'test1',
'test2',
'test3',
'test4' ]
}
but .serialize() does not work with file submissions.
So, I'm wondering what the best way to support this. My requirements are that the form cannot leave the page upon submit, so I felt Ajax was the right way to go.
Is there any way for FormData to play nicely with input arrays and NodeJS Express? Or any sort of work around for this? I'd really rather not have to do some sort of string finagling when .serialize() does it so nicely.