ASP.NET如何检查图片URL是否存在?

9

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

最好的方法是如何检查图像URL是否有效?


1
在 img 标签中有 onerror 属性。 - jjchiw
抱歉,在回答之前我没有看到这个问题。 - Mike Miller
4个回答

11

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

<html>
    <body>
        <img src="<dynamic handler url>" alt="My Username" onError="this.src='defaultProfile.jpg';" />
    </body>
</html>
这是在ASP.NET中完成此操作的方法。
设计器 -
<asp:Image ImageUrl="NonexistentImage.Jpg" ID="profileImage" Height="50" Width="50" runat=server />

代码后端(c#)

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

对我来说,这个方法完美地运行。


您可以通过将其添加到属性集合中来设置它,具体请参见http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.webcontrol.attributes.aspx。 - Mike Miller
onError似乎对<img>或asp:image都不起作用,它实际上说onError不是<img>的有效元素。 - sd_dracula
它不是w3c标准的一部分,但大多数浏览器都支持它。即使在2001年-http://lists.w3.org/Archives/Public/www-html/2001Sep/0084.html。有很多人在使用它(http://blog.sociomantic.com/2010/07/html-onerror-the-good-the-bad-and-the-ugly/),所以很可能是asp图像控件引起的问题。 - Mike Miller
那个完美地运行了。我只是在字符串中有一些语法错误。谢谢。 - sd_dracula
1
ASP VB代码隐藏图像如果未找到。 myImage.Attributes("onerror") = "this.style.visibility=""hidden"";" - Brent
显示剩余2条评论

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;

您忘记关闭响应对象,这会导致问题。 - Aristos

2
你可以很容易地在jQuery中实现这一点。
$("#myImage")
    .load(function() { alert("it loaded ok") })
    .error(function() {  $(this).attr("src", alternateImage)  });

0

从代码后台检查

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接