Validating Image Dimensions Before Upload with JavaScript
To ensure users adhere to image size guidelines, it's essential to check image width and height before uploading.
File Validation
Your existing code validates the file type and size. To add image dimension checks, you need to create an image object from the uploaded file.
Using createObjectURL()
The createObjectURL() method in modern browsers allows you to create a temporary URL object from the file. You can then load the image asynchronously using an Image object:
<code class="javascript">const file = target.files[0]; const objectUrl = URL.createObjectURL(file); const img = new Image(); img.onload = () => { console.log(`Width: ${img.width}, Height: ${img.height}`); URL.revokeObjectURL(objectUrl); }; img.src = objectUrl;</code>
Considerations
Demo
See a live example here: https://jsfiddle.net/4N6D9/1/
Note: As mentioned earlier, this approach is browser-specific and may not work consistently across all platforms.
The above is the detailed content of How to Validate Image Dimensions Before Upload with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!