asp.net check if imageURL exists

孤者浪人 提交于 2019-12-05 07:16:59

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.

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;

You can acheive this in jQuery quite easily.

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

From the code-behind check

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!