我正在尝试从另一个内部网站获取用户的缩略图,但其中一些不符合预定义格式,这意味着我想要加载默认缩略图。
最好的方法是如何检查图像URL是否有效?
根据您获取图像的方式,这种方法可能会有所不同。
<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;
$("#myImage")
.load(function() { alert("it loaded ok") })
.error(function() { $(this).attr("src", alternateImage) });
从代码后台检查
File.Exists(Server.MapPath("file path"))