asp.net检查imageURL是否存在

我试图从另一个内部网站点获取用户的缩略图,但其中一些不遵循预定义的格式,这意味着我想要加载默认缩略图。

什么是检查图像URL是否有效的最佳方法?

根据您获取图像的方式,这可能会有所不同

  My Username   

这是你在ASP.NET中的方法。

设计师 –

  

代码背后(c#)

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

这对我来说很完美。

 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; 

你可以很容易地在jQuery中实现这一点。

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

从代码隐藏检查

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

如果返回true,则分配值,否则分配默认缩略图。