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:
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); });
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!