asp.net check if imageURL exists
Asked Answered
G

4

9

I am trying to get a user's thumbnail from another intranet site but some of them do not follow the pre-defined format meaning I would want to load up a default thumbnail instead.

Whats the best way to check if an image URL is valid?

Gil answered 30/5, 2012 at 8:53 Comment(2)
#1589354 there is the onerror attribute in the img tagInterviewer
^sorry I didn't see this before answering.Hafer
H
11

Depending on how you are getting your images a variation of this might work

<html>
    <body>
        <img src="<dynamic handler url>" alt="My Username" onError="this.src='defaultProfile.jpg';" />
    </body>
</html>

This is how you would do it in ASP.NET.

Designer -

<asp:Image ImageUrl="NonexistentImage.Jpg" ID="profileImage" Height="50" Width="50" runat=server />

Code Behind (c#)

profileImage.Attributes["onerror"] = "this.src='http://www.cs.uofs.edu/~olivetoj2/blah.jpg';";

This works perfectly for me.

Hafer answered 30/5, 2012 at 9:3 Comment(7)
Thanks. I will try this. the <asp:image> does not have this attribute.Gil
you can set it by adding it to attributes collections, msdn.microsoft.com/en-us/library/…Hafer
onError doesnt seem to work for either <img> or <asp:image> it actually said onError is not a valid element of <img>Gil
It isn't part of the w3c standard but most browsers support it. Even back in 2001 - lists.w3.org/Archives/Public/www-html/2001Sep/0084.html. There are a lot of people using it (blog.sociomantic.com/2010/07/…) so it's likely to be the asp image control causing the issue.Hafer
That works perfectly. I just had some syntax errors within the string. Thank you.Gil
No worries, probably should have put the asp.net example first.Hafer
ASP VB code behind hide image if not found. myImage.Attributes("onerror") = "this.style.visibility=""hidden"";"Millerite
K
2
WebRequest webRequest = WebRequest.Create(url);  
WebResponse webResponse;
try 
{
  webResponse = webRequest.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
  return 0;
} 
return 1;
Kistler answered 30/5, 2012 at 8:59 Comment(1)
You have forget to close the response objects and this lead to problems.Passport
R
2

You can acheive this in jQuery quite easily.

$("#myImage")
    .load(function() { alert("it loaded ok") })
    .error(function() {  $(this).attr("src", alternateImage)  });
Reimers answered 30/5, 2012 at 9:3 Comment(0)
J
0

From the code-behind check

File.Exists(Server.MapPath("file path"))

If it returns true then assign the value, otherwise assign your default thumbnail.

Jeaniejeanine answered 30/5, 2012 at 9:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.