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
Mary-Kate OlsenOriginal
2024-12-15 20:56:16735browse

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.

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!

Statement:
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