Home > Web Front-end > JS Tutorial > How Can I Preview File Size, Image Dimensions Before Uploading with HTML5 and JavaScript?

How Can I Preview File Size, Image Dimensions Before Uploading with HTML5 and JavaScript?

Linda Hamilton
Release: 2024-11-26 11:51:11
Original
747 people have browsed it

How Can I Preview File Size, Image Dimensions Before Uploading with HTML5 and JavaScript?

Preview File Metadata Before Uploading with HTML5 and JavaScript

Problem:

How can you obtain the file size, image width, and height before uploading a file to your website using jQuery or JavaScript?

Solution:

Utilizing HTML5's File API, you can access the following information before the file upload:

File Size:

  • Through the file.size property, which returns the file size in bytes.

Image Width and Height:

  • For images, you can use the URL API to create a temporary URL for the image blob and load it into a temporary image element.
  • Once the image loads, you can access its width and height properties before revoking the object URL to free up memory.

Example Using URL API:

The code snippet below demonstrates how to preview image metadata using the URL API:

const readImage = file => {
  if (!(/^image\/(png|jpe?g|gif)$/).test(file.type))
    return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);

  const img = new Image();
  img.addEventListener('load', () => {
    EL_preview.appendChild(img);
    EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size / 1024)}KB<div>`);
    window.URL.revokeObjectURL(img.src); // Free some memory
  });
  img.src = window.URL.createObjectURL(file);
};

EL_browse.addEventListener('change', ev => {
  EL_preview.innerHTML = ''; // Remove old images and data
  const files = ev.target.files;
  if (!files || !files[0]) return alert('File upload not supported');
  [...files].forEach(readImage);
});
Copy after login

The above is the detailed content of How Can I Preview File Size, Image Dimensions Before Uploading with 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