Obtaining file size and image dimensions before uploading is essential for validating and managing submissions. Here's how to achieve this using HTML5 and JavaScript:
The File API provides a mechanism to access information about files selected by the user. This can be leveraged to retrieve file size, image height, and width. Consider the following example:
const browseInput = document.getElementById('browse'); const previewContainer = document.getElementById('preview'); const handleFileSelection = (event) => { previewContainer.innerHTML = ''; const files = event.target.files; if (!files || files.length === 0) { alert('No files selected!'); return; } for (const file of files) { // Check if the file is an image if (!file.type.startsWith('image/')) { previewContainer.insertAdjacentHTML('beforeend', `Unsupported format: ${file.name}<br>`); continue; } // Create an image element to calculate width and height const img = new Image(); img.onload = () => { previewContainer.appendChild(img); const fileInfo = ` <div> ${file.name} ${img.width} × ${img.height} ${file.type} ${Math.round(file.size / 1024)} KB </div> `; previewContainer.insertAdjacentHTML('beforeend', fileInfo); }; // Load the image and release the URL when done img.src = URL.createObjectURL(file); } }; browseInput.addEventListener('change', handleFileSelection);
This approach allows you to get file size, image width, and height before uploading, enabling better control over accepted file types and dimensions. Additionally, you can use this information for validation and display purposes, such as providing a preview of the selected images before submission.
The above is the detailed content of How Can I Get File Size, Image Width, and Height Before Uploading a File Using HTML5 and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!