I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.
相关问题
- Views base64 encoded blob in HTML with PHP
- How to get the background from multiple images by
- CV2 Image Error: error: (-215:Assertion failed) !s
- UrlEncodeUnicode and browser navigation errors
- Improve converting string to readable urls
相关文章
- Optimization techniques for backtracking regex imp
- Regex to check for new line
- Use savefig in Python with string and iterative in
- Where does this quality loss on Images come from?
- Specifying image dimensions in HTML vs CSS for pag
- How to insert pictures into each individual bar in
- Allow only 2 decimal points entry to a textbox usi
- How do I append metadata to an image in Matlab?
Actually.
Why are you checking the URL? That's no guarantee what you're going to get is an image, and no guarantee that the things you're rejecting aren't images. Try performing a HEAD request on it, and see what content-type it actually is.
In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.
If you are keen on doing this, though, check out this question:
Getting parts of a URL (Regex)
Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like
If you really want to be sure, grabbing the first kilobyte or two of the given URL should be sufficient to determine everything you need to know about the image.
Here's an example of how you can get that information, using Python, and here's an example of it being put to use, as a Django form field which allows you to easily validate an image's existence, filesize, dimensions and format, given its URL.
That's a (slightly modified) version of the official URI parsing regexp from RFC 2396. It allows for
#fragments
and?querystrings
to appear after the filename, which may or may not be what you want. It also matches any valid domain, includinglocalhost
, which again might not be what you want, but it could be modified.A more traditional regexp for this might look like the below.
EDIT See my other comment, which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for
karma-whoringcompleteness reasons.This will mach all images from this string:
Test your regex here: https://regex101.com/r/l2Zt7S/1