开发者

How can I test if a URL is a valid image (in javascript)?

开发者 https://www.devze.com 2023-01-16 22:14 出处:网络
When submitting a form, I want to make sure a field is a valid image URL. I could make an AJAX endpoint on my server which CURLs the URL and p开发者_如何学Pythonarses the output with an image library

When submitting a form, I want to make sure a field is a valid image URL.

I could make an AJAX endpoint on my server which CURLs the URL and p开发者_如何学Pythonarses the output with an image library, but that feels a bit of overkill.

Could I get away with making an <img> element then synchronously check the response somehow?


You can make an <img> element and handle its onerror and onload events.

If the load event fires, it's a valid image; if the error event fires, it isn't.
This even works across domains.


Do this, the following code will replace any non-image with a default image.

<img src="xx" onerror="this.src = '/images/default.png'">
0

精彩评论

暂无评论...
验证码 换一张
取 消