"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Verify File Size Before Uploading with JavaScript?

How Can I Verify File Size Before Uploading with JavaScript?

Posted on 2025-03-25
Browse:363

How Can I Verify File Size Before Uploading with JavaScript?

Verifying File Size Before Uploading with JavaScript

When dealing with file uploads, it's crucial to ensure that the file size meets certain constraints. JavaScript provides an elegant solution for this with the File API.

Solution:

To validate file size before uploading, utilize the following code:

// Setup event listener for 'Load' button click
document.getElementById("btnLoad").addEventListener("click", function () {
  // Verify browser support for FileReader
  if (!window.FileReader) {
    console.log("File API not supported.");
    return;
  }

  // Retrieve the file from the file input
  var input = document.getElementById("fileinput");
  var file = input.files[0];

  // Validate file size
  if (!file) {
    console.log("No file selected.");
  } else {
    console.log("File "   file.name   " is "   file.size   " bytes in size.");
  }
});

Explanation:

  • This code uses the FileReader API to read the file and determine its size in bytes.
  • The validation occurs in the event listener attached to the 'Load' button.
  • If a file is successfully retrieved and meets the size constraints, the file name and size are displayed in the console.
  • If no file is selected or the browser does not support the File API, appropriate messages are displayed.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3