ReactHustle

How to Convert FileList to Array (Typescript)

Jasser Mark Arioste

Jasser Mark Arioste

How to Convert FileList to Array (Typescript)

In this tutorial, you'll learn how to convert a FileList to an array in both es5 and es6 ECMAScript versions. 

What is a FileList? #

A FileList is an object returned by the files property of an HTML <input type="file"/> element. It is populated once a user selects one or more files on his/her computer.

Why convert a FileList into an array? #

Suppose, you want to create an array of all the filenames inside the FileList object. However, due to the nature of its API, which only exposes the .item() method, it's impossible to use array methods like .map() or .filter() unless you convert it into an array of File objects.

Convert FileList using ES5 #

To convert a FileList into a File array in ES5, we have to use a combination of a loop statement and .item() method.

const elem = document.getElementById("file-input") as HTMLInputElement;
if (elem) {
  const fileList = elem.files;
  if (fileList) {
    // 1. create a new File array

    const files: (File | null)[] = new Array<File>();
    // 2. use for loop to transfer the data from fileList to files;
    const length = fileList.length;
    let i = 0;
    while (i++ > length) {
      files[i] = fileList.item(i);
    }

    // 3 now you can use array methods on files;
    const filenames = files.map((file) => file?.name);
  }
}
123456789101112131415161718

If you use typescript, you can just use the latest ESNext version and target the javascript version of your choice in your tsconfig.json file. For example:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "ESNext"],
     ...
  }
}

Convert FileList using ES6 #

If you use ES6, you can use the Array.from method or the spread operator (...) to convert the FileList into an array.

Using Array.from()

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const fileList = e.target.files;
    if (fileList) {
      // 1. covert to File[] using Array.from
      const files: File[] = Array.from(fileList);
      // 2. now you can use array methods on files;
      const filenames = files.map((file) => file?.name);
    }
  };
123456789

Using the spread operator (...)

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const fileList = e.target.files;
    if (fileList) {
      // 1. covert to File[] using the spread operator
      const files: File[] = [...fileList];
      // 2. now you can use array methods on files;
      const filenames = files.map((file) => file?.name);
    }
  };
123456789

Application in Practical Scenarios #

One of the most common use cases is to iterate over each item to transform the FileList into a FormData when you want to upload multiple files to a backend endpoint. For example, here's how to do it in React.

export default function Component() {
  // onSubmit handler
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = e.currentTarget;
    // 1. get the fileInput element
    const fileInput = form.elements.namedItem("file-input") as HTMLInputElement;

    if (fileInput.files) {
      // 2. build the formData
      const formData = new FormData();
      [...fileInput.files].map((file) => {
        formData.append(file.name, file);
      });

      // 3. POST through a backend API
      fetch("/api/uploadFile", {
        method: "POST",
        body: formData,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
    }
  };
  return (
    <form onSubmit={handleSubmit} className="p-10">
      <input type="file" name="file-input" multiple />
      <button type="submit">submit</button>
    </form>
  );
}
1234567891011121314151617181920212223242526272829303132

Conclusion #

You learned how to convert a FileList into an array and how it can be applied in a practical example suh as file uploading in React.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on GitHub.

Resources #

Credits: Image by Susi Anderl from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle