asp.net check if imageURL exists

18.5k Views Asked by At

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?

4

There are 4 best solutions below

7
On BEST ANSWER

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.

1
On
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;
0
On

You can acheive this in jQuery quite easily.

$("#myImage")
    .load(function() { alert("it loaded ok") })
    .error(function() {  $(this).attr("src", alternateImage)  });
0
On

From the code-behind check

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

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