Home >Web Front-end >JS Tutorial >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); });
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!