Home > Web Front-end > JS Tutorial > How to Validate Image Dimensions Before Upload with JavaScript?

How to Validate Image Dimensions Before Upload with JavaScript?

Linda Hamilton
Release: 2024-11-03 19:01:29
Original
532 people have browsed it

How to Validate Image Dimensions Before Upload with JavaScript?

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>
Copy after login

Considerations

  • createObjectURL() is only supported in modern browsers like Firefox, Chrome, and Opera.
  • The URL.revokeObjectURL() method must be called to release the temporary URL when done.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template