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?

sd_dracula
  • 3,796
  • 28
  • 87
  • 158

4 Answers4

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.

Mike Miller
  • 16,195
  • 1
  • 20
  • 27
  • Thanks. I will try this. the does not have this attribute. – sd_dracula May 30 '12 at 09:11
  • you can set it by adding it to attributes collections, http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.attributes.aspx – Mike Miller May 30 '12 at 09:16
  • onError doesnt seem to work for either or it actually said onError is not a valid element of – sd_dracula May 30 '12 at 09:29
  • It isn't part of the w3c standard but most browsers support it. Even back in 2001 - http://lists.w3.org/Archives/Public/www-html/2001Sep/0084.html. There are a lot of people using it (http://blog.sociomantic.com/2010/07/html-onerror-the-good-the-bad-and-the-ugly/) so it's likely to be the asp image control causing the issue. – Mike Miller May 30 '12 at 09:35
  • That works perfectly. I just had some syntax errors within the string. Thank you. – sd_dracula May 30 '12 at 09:59
  • No worries, probably should have put the asp.net example first. – Mike Miller May 30 '12 at 10:01
  • 1
    ASP VB code behind hide image if not found. myImage.Attributes("onerror") = "this.style.visibility=""hidden"";" – Brent Dec 10 '13 at 14:11
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;
bilagi
  • 21
  • 1
2

You can acheive this in jQuery quite easily.

$("#myImage")
    .load(function() { alert("it loaded ok") })
    .error(function() {  $(this).attr("src", alternateImage)  });
Jeff Watkins
  • 6,343
  • 16
  • 19
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.

Matthias
  • 7,432
  • 6
  • 55
  • 88
dotnetmirror.com
  • 293
  • 2
  • 10