0

I have a form with a field that has multi-select enabled. I'm able to get the form data and see the array containing all the files that were selected via the file field.

I'm trying to replace the file array with my selected_files array that I have modified, but when I use FormData.set, it is setting my array as a string it looks like. Please see the below example.

var form = new FormData(document.getElementById("asset-create-form"));
var files = form.getAll('file')
// file field has multiselect enabled so enduser can select more than one file
console.log(files)
>> [File, File, File, File, File] (5)
console.log(selected_files)
>> [File, File, File, File, File] (5)
form.set('file', selected_files)
new_files = form.getAll('file')
console.log(new_files)
>> ["[object File],[object File],[object File],[object File],[object File]"] (1)

Why is this a string? How can I set my selected_files array to the file field?

If the set function can only set to a variable, then is there a workaround?

2
  • Does this answer your question? How use formData.append for a array in typescript Commented Apr 1, 2021 at 19:33
  • Is your question answered? If not, please comment accordingly. If yes, please pick an answer. If it was helpful, consider an upvote. Commented Apr 1, 2021 at 20:12

1 Answer 1

0

If the sent value is different than String or Blob it will be automatically converted to String.
https://developer.mozilla.org/en-US/docs/Web/API/FormData/set#example

The array you're trying to set is neither String nor Blob, so it it converted.

In other words: The only values FormData can hold is String (any regular form field) and Blob (input type=file), meaning form data cannot hold other data types such as arrays, numbers, booleans, null, objects etc.

As for your second question, simply use FormData.prototype.append in a loop:

var form = new FormData(document.getElementById("asset-create-form"));
form.delete('file'); // delete the files already in the form data
selected_files.forEach(file => form.append('file', file));
Sign up to request clarification or add additional context in comments.

6 Comments

but then why does console.log(files) return an array with all the selected files in it
Consider reading the basic documentation before asking on StackOverflow. developer.mozilla.org/en-US/docs/Web/API/FormData/… [getAll] Returns an array of FormDataEntryValues whose key matches the value passed in the name parameter.
Where is selectedFiles retrieved from? How does it relate to files?
selectedFiles is an array structured the same as the files array
Any you want to fully replace whatever form data with key file is already there?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.