Home > Web Front-end > JS Tutorial > body text

How Can I Get File Size, Image Width, and Height Before Uploading a File Using HTML5 and JavaScript?

Linda Hamilton
Release: 2024-11-25 10:40:11
Original
843 people have browsed it

How Can I Get File Size, Image Width, and Height Before Uploading a File Using HTML5 and JavaScript?

Get File Size, Image Width, and Height Before Upload

Obtaining file size and image dimensions before uploading is essential for validating and managing submissions. Here's how to achieve this using HTML5 and JavaScript:

Using HTML5 File API

The File API provides a mechanism to access information about files selected by the user. This can be leveraged to retrieve file size, image height, and width. Consider the following example:

const browseInput = document.getElementById('browse');
const previewContainer = document.getElementById('preview');

const handleFileSelection = (event) => {
  previewContainer.innerHTML = '';
  const files = event.target.files;

  if (!files || files.length === 0) {
    alert('No files selected!');
    return;
  }

  for (const file of files) {
    // Check if the file is an image
    if (!file.type.startsWith('image/')) {
      previewContainer.insertAdjacentHTML('beforeend', `Unsupported format: ${file.name}<br>`);
      continue;
    }

    // Create an image element to calculate width and height
    const img = new Image();
    img.onload = () => {
      previewContainer.appendChild(img);
      const fileInfo = `
        <div>
          ${file.name}
          ${img.width} × ${img.height}
          ${file.type}
          ${Math.round(file.size / 1024)} KB
        </div>
      `;
      previewContainer.insertAdjacentHTML('beforeend', fileInfo);
    };

    // Load the image and release the URL when done
    img.src = URL.createObjectURL(file);
  }
};

browseInput.addEventListener('change', handleFileSelection);
Copy after login

Further Possibilities

This approach allows you to get file size, image width, and height before uploading, enabling better control over accepted file types and dimensions. Additionally, you can use this information for validation and display purposes, such as providing a preview of the selected images before submission.

The above is the detailed content of How Can I Get File Size, Image Width, and Height Before Uploading a File Using HTML5 and 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