I need to verify an image url to check whether the url is an image of any of these extensions:- jpeg, jpg, gif, png. Example:- when we verify this url http://www.example.com/asdf.jpg it should give us true value and with url like this http://www.example.com/asdf.php should return false. How can we do this in javascript and also i want to check the content type of url. So that we can say whether the url is an image or not.
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to get the background from multiple images by
- void before promise syntax
use the HEAD http request method to check the contenttype...
to check whether the string contains that extenstions you can use the inArray method,
edit: updated typo
You can use a regular expression like this to check the file extension:
This checks to see if the url ends in any of those four extensions.
I know of no way from javascript in the client to verify the content-type of a URL that isn't on the same domain as the web page because you can't use ajax outside of the domain of the web page. As best I know, you'd have to ship the URL to a server process and have it download the image, get the content type and return that to you.
But, you can check to see if an image tag can load the URL by using a function like this:
This function will call your callback at some future time with two arguments: the original URL and a result ("success", "error" or "timeout"). You can see this work on several URLs, some good and some bad, here: http://jsfiddle.net/jfriend00/qKtra/
And, since this is now the era of Promises, here's a version that returns a promise:
And, a jsFiddle demo: http://jsfiddle.net/jfriend00/vhtzghkd/