Home >Web Front-end >JS Tutorial >How to Get File Size and Image Dimensions Before Upload with JavaScript?

How to Get File Size and Image Dimensions Before Upload with JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 12:39:10832browse

How to Get File Size and Image Dimensions Before Upload with JavaScript?

File Size and Image Dimensions Before Upload Using jQuery or JavaScript

To obtain the file size, image width, and height before uploading to a website, utilize the File API provided by HTML5 and JavaScript.

Utilizing URL API

The Blob objects will be represented as URLs for image sources.

<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">
const EL_browse = document.getElementById('browse');
const EL_preview = document.getElementById('preview');

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);
});
#preview img { max-height: 100px; }
<input>

The above is the detailed content of How to Get File Size and Image Dimensions Before Upload 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