Home > Web Front-end > JS Tutorial > How Can I Get File Size, Image Dimensions, and Type Before Uploading in HTML5?

How Can I Get File Size, Image Dimensions, and Type Before Uploading in HTML5?

Linda Hamilton
Release: 2024-12-27 11:42:12
Original
901 people have browsed it

How Can I Get File Size, Image Dimensions, and Type Before Uploading in HTML5?

Getting File Size, Image Width, and Height Before Upload

With the advent of HTML5 and the File API, obtaining the file size, image width, and height before upload has become much simpler.

Using URL API

This method utilizes the URL API to create a URL representation of the uploaded file:

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

This allows for displaying the image as a preview and displaying details such as the filename, dimensions, file type, and size before uploading.

The above is the detailed content of How Can I Get File Size, Image Dimensions, and Type Before Uploading in HTML5?. 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