Home > Web Front-end > JS Tutorial > How Can I Verify File Size Before Uploading with JavaScript?

How Can I Verify File Size Before Uploading with JavaScript?

Mary-Kate Olsen
Release: 2024-12-15 20:56:16
Original
734 people have browsed it

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.");
  }
});
Copy after login

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.

The above is the detailed content of How Can I Verify File Size Before Uploading with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template