Getting the Size of the Selected File Using JavaScript

When working with file uploads in web applications, it's often necessary to retrieve information about the selected files, such as their size.

JavaScript provides a straightforward way to accomplish this by utilizing the File object and the FileList interface.

In this article, we'll explore how to get the size of the selected file using JavaScript.

Input Element for File Upload

To enable file uploads in a web page, you can use the <input> element with the type attribute set to "file".

Here's an example:

<input type="file" id="fileInput" onchange="handleFileSelection()">

In this code:

Using JavaScript to Get File Size

Let's implement the JavaScript function handleFileSelection() to retrieve the size of the selected file:

function handleFileSelection() {
  // Get the file input element
  const fileInput = document.getElementById('fileInput');

  // Check if files are selected
  if (fileInput.files.length > 0) {
    // Access the first selected file
    const selectedFile = fileInput.files[0];

    // Get the size of the selected file (in bytes)
    const fileSizeInBytes = selectedFile.size;

    // Convert bytes to kilobytes (optional)
    const fileSizeInKB = fileSizeInBytes / 1024;

    console.log(`Selected file size: ${fileSizeInBytes} bytes (${fileSizeInKB} KB)`);
  } else {
    console.log('No file selected.');
  }
}

In this code:

Full Example

Let's put everything together in a complete HTML example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Size Example</title>
</head>
<body>

  <input type="file" id="fileInput" onchange="handleFileSelection()">

  <script>
    function handleFileSelection() {
      // Get the file input element
      const fileInput = document.getElementById('fileInput');

      // Check if files are selected
      if (fileInput.files.length > 0) {
        // Access the first selected file
        const selectedFile = fileInput.files[0];

        // Get the size of the selected file (in bytes)
        const fileSizeInBytes = selectedFile.size;

        // Convert bytes to kilobytes (optional)
        const fileSizeInKB = fileSizeInBytes / 1024;

        console.log(`Selected file size: ${fileSizeInBytes} bytes (${fileSizeInKB} KB)`);
      } else {
        console.log('No file selected.');
      }
    }
  </script>
</body>
</html>

In this example:

Conclusion

Getting the size of a selected file is a common task when working with file uploads in web development.

JavaScript, along with the File API, provides a simple and effective way to retrieve file size information.

Incorporate this knowledge into your file upload workflows to enhance user interactions and provide meaningful feedback in your web applications.