Javascript FileList example | How to modify files in input type file?


FileList is an object in javascript used to manipulate the file upload in javascript applications

What is a FIleList in javascript?

FileList is an an object in Javascript to read file metadata and content from input type file control on user form. This also returns when an file is uploaded using drag and drop API in javascript

Suppose you have input type file on a form

<input type=file multiple>

Input type file used to upload a files from a browser. Multiple options enable to upload multiple files.

FileList object holds the file information When user upload an file(s),

Following is an example for reading the input type in pure javascript

  • inputfileselector is assigned by using input selector tag
  • inputfileselector.files or event.target.files returns FileList object
  • FileList object contains List of File objects

<!DOCTYPE html>
<html>

<body>
  <h1>Input file example</h1>

<input type="file"  multiple>
<script>
  const inputfileselector = document.querySelector('input');
  inputfileselector.addEventListener('change', (event) => {
    const fileList = event.target.files;
    console.log(fileList);
        const fileList1 = inputfileselector.files;
    console.log(fileList1);
  });
</script>

</html>

Output

FileList {0: File, length: 1}
FileList {0: File, length: 1}
0: File {name: "Das.png", lastModified: 1625064498536, lastModifiedDate: Wed Jun 30 2021 20:18:18 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 859658, …}
length: 1

Even though FileList contains list of files, It is not array type object, But It provides length method to return file count.

This tutorials list out various examples of using FIleList

How to Convert FileList into Array in javascript?

FileList is an object not array object. Why filelist is an array? Array can be mutated or modified and FileLlist can not be modified. Because of this reason most of the DOM related classes like NodeList, HTMLCollection and FileList are objects. How do you convert FileList into an array?

const arrayFiles = Array.from(event.target.files)

How to iterate FileList objects in javascript?

Since FileList is not an Array, Then how do you iterate an FIleList object You can use FileList with index property to get an each file object.

THere are multiple ways you can iterate

using for loop

It is simple to use for loop syntax

Here is an example print upload file names

<script>
  const inputfileselector = document.querySelector('input');
  inputfileselector.addEventListener('change', (event) => {
    const fileList = event.target.files;
for (var i = 0; i < fileList.length; i++) {
    console.log(fileList[i].name);
}

  });
</script>

for of loop

This is another way syntax introduced in javascript with for of syntax

<script>
  const inputfileselector = document.querySelector('input');
  inputfileselector.addEventListener('change', (event) => {
    const fileList = event.target.files;
for (let file of fileList) {
    console.log(file.name);
}

  });
</script>

Can we use forEach with FileList object?

Yes we can do it in different way by converting into array

using forEach loop

forEach loop introduced in Array in EcmaScript 6 language

  • First convert FileList into Array
  • then use ES6 forEach method to iterate each file object
<script>
  const inputfileselector = document.querySelector('input');
  inputfileselector.addEventListener('change', (event) => {
    const fileList = event.target.files;
    Array.from(field.photo.files).forEach(file => {     
    console.log(file.name);
 });


  });
</script>

How do remove a file from FileList in javascript?

When you are working with file upload, You need to add remove functionality before upload to backend.

An upload file in javascript returns FileList, So you have to remove an file from FileList.

Here is an sequence of steps

  • First convert FileList into an Array object
  • Remove an file from Array using splice method , returns new list without an file
  • Assign input element files with new list

How to read file name size and type in javascript

FileList contains list of file object, each file object holds meta information of an file

  • File.name returns name of an file

  • File.type It returns MIME type ie file extension. For example,an Image files returns type=Image/png and other types are image/svg+xml application/x-zip-compressed, text/html , application/pdf etc.

  • FIle.size It returns size in bytes

    Here is an example

Output:

abc.png
1552681
image/png

How to check if input file upload is empty in javascript?

Some times, You want to display the message like “No files selected” during input type file.

You can use length method to check FileList object is empty or not

<script>
  const inputfileselector = document.querySelector('input');
if( inputfileselector.files.length == 0 ){
    console.log("no files selected");
}
</script>

How do read file content from client browser in javascript?

This examples read the file content into an binary string

Here are sequence of steps for converting file into binary string.

  • Read input file using input selector
  • select First file from FileList object
  • Create a FileReader object to read the file object
  • readAsBinaryString read the file content and convert to binary string

Example

<script>
  const inputfileselector = document.querySelector('input');
if( inputfileselector.files.length == 0 ){
    console.log("no files selected");
}
let content="";
    var firstFile = inputfileselector.files[0];
    var reader = new FileReader();

    reader.addEventListener('load', function (e) {
      content = e.target.result;

    });
    reader.readAsBinaryString(firstFile);
</script>

The same way we can use Blob object to/from file of FileList object.

Conclusion

FileList is important DOM class to read file contents from input type file control on browser. Documented few examples about File list

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Javascript - Array vs JSON vs Object basics with Examples

How to convert json to/from  object in angular|Typescript 

Angular ngFor index - How to get current last even and odd index?

How to convert Set to String space separated in javascript

Learn Service Worker for application offline access

How to Format array of dates in typescript Angular example

In this post, you learn writing comments in Angular and typescript. You can also write single multiline and documentation comments in Typescript. This includes declare comments in Angular typescript and template HTML components.