Skip to content

Arrays of files or FileList objects with only one element in them are not parsed as arrays #178

@islami00

Description

@islami00

Description

When an array containing only one File or a FileList of only one file is submitted, the resulting FormData from generateFormData is not an array. This is because there is only one FormData entry for the file.

Suggested solution

I would suggest:

  1. leveraging the existing logic in parseFormData that checks for [] suffix in keys and transforms the value to an array to handle file lists with only one element in them.
  2. or Flattening the data that's being transformed to formData using something like flattenObject as a more general approach to support objects of any shape/depth

Patch

I used the following patch of remix-hook-form@7.1.1 to fix the issue:

diff --git a/dist/chunk-RDVJQORD.js b/dist/chunk-RDVJQORD.js
index ee1875f1597cca58deaf228f4ed660857f3af092..597d94bc90bfe7a20d8fe2af29ea1f7ce88d87e9 100644
--- a/dist/chunk-RDVJQORD.js
+++ b/dist/chunk-RDVJQORD.js
@@ -92,12 +92,20 @@ var createFormData = (data, stringifyAll = true) => {
       continue;
     }
     if (typeof FileList !== "undefined" && value instanceof FileList) {
+      if (value.length === 1) {
+        formData.append(`${key}[]`, value[0]);
+        continue;
+      }
       for (let i = 0; i < value.length; i++) {
         formData.append(key, value[i]);
       }
       continue;
     }
     if (Array.isArray(value) && value.length > 0 && value.every((item) => item instanceof File || item instanceof Blob)) {
+      if (value.length === 1) {
+        formData.append(`${key}[]`, value[0]);
+        continue;
+      }
       for (let i = 0; i < value.length; i++) {
         formData.append(key, value[i]);
       }
diff --git a/dist/index.cjs b/dist/index.cjs
index c8964f29d77f11b8a162bb785c97a1e062978734..1ba4672452c7b9a53cc1224da73ed7f178847a72 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -136,12 +136,20 @@ var createFormData = (data, stringifyAll = true) => {
       continue;
     }
     if (typeof FileList !== "undefined" && value instanceof FileList) {
+      if (value.length === 1) {
+        formData.append(`${key}[]`, value[0]);
+        continue;
+      }
       for (let i = 0; i < value.length; i++) {
         formData.append(key, value[i]);
       }
       continue;
     }
     if (Array.isArray(value) && value.length > 0 && value.every((item) => item instanceof File || item instanceof Blob)) {
+      if (value.length === 1) {
+        formData.append(`${key}[]`, value[0]);
+        continue;
+      }
       for (let i = 0; i < value.length; i++) {
         formData.append(key, value[i]);
       }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions