I'm trying to use the native Fetch and FormData APIs to upload multiple files at once to the server but I can't for the life of me get it to work. Here's what I've got:
// acceptedFiles are File objects coming from `react-dropzone`.
function handleSubmit(acceptedFiles) {
const data = new FormData();
for (const file of acceptedFiles) {
data.append('files', file, file.name);
}
return fetch('https://example.com/api/upload', {
method: 'POST',
body: data,
});
}
But what my Rails server receives is this:
Parameters: {"files"=>#
<ActionDispatch::Http::UploadedFile:0x00007feb347becc0 @tempfile=#
<Tempfile:/var/folders/kl/y1jrp7zs55sbx075jjjl3p280000gn/T/RackMultipart201
71112-6486-1ftkufy.mp4>, @original_filename="SampleVideo_1280x720_5mb.mp4",
@content_type="video/mp4", @headers="Content-Disposition: form-data;
name=\"files\"; filename=\"SampleVideo_1280x720_5mb.mp4\"\r\nContent-Type:
video/mp4\r\n">}
In other words, it looks like files
is actually just one file. But the docs for FormData
say that append should append multiple files.
So what's going wrong?
You could add a new <input type="file"> whenever you finished uploading the previous files and hide the previous input. This way you keep adding a new input every time you want to add more files and prevent the previous input from being overwritten. And it doesn't require you to use AJAX.
The solution was to change files
to files[]
:
// acceptedFiles are File objects coming from `react-dropzone`.
function handleSubmit(acceptedFiles) {
const data = new FormData();
for (const file of acceptedFiles) {
data.append('files[]', file, file.name);
}
return fetch('https://example.com/api/upload', {
method: 'POST',
body: data,
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With