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

How Can I Check File Size Before Uploading with JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 11:52:10369browse

How Can I Check File Size Before Uploading with JavaScript?

Checking File Size Before Upload in JavaScript

With JavaScript's advanced functionality, it's possible to validate file size before uploading. This ensures adherence to size constraints, preventing server-side issues or user frustrations due to large file sizes.

Solution: The File API

The File API provides an easy way to interact with files on the client side. Here's a practical example:

document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
  // Check for browser support
  if (!window.FileReader) {
    console.log("File API not supported");
    return;
  }

  var input = document.getElementById("fileinput");

  // Check for selected file
  if (!input.files || !input.files[0]) {
    addPara("Select a file first");
  } else {
    var file = input.files[0];
    addPara("File " + file.name + " is " + file.size + " bytes in size");
  }
});

This script:

  1. Listens for a click on the "Load" button.
  2. Checks for File API support and warns if not available.
  3. Accesses the selected file from the element.
  4. Logs the file size in the document body.

By integrating this script into your upload form, you can effectively prevent large file submissions and provide a seamless user experience.

The above is the detailed content of How Can I Check 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