asp.net 检查图像网址是否存在
本文关键字:是否 存在 图像 net 检查 asp | 更新日期: 2023-09-27 18:35:55
我正在尝试从另一个内部站点获取用户的缩略图,但其中一些不遵循预定义的格式,这意味着我想加载默认缩略图。
检查图片网址是否有效的最佳方法是什么?
根据您获取图像的方式,此变体可能会起作用
<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';";
这对我来说非常有效。
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,则分配值,否则分配默认缩略图。