[英]asp.net check if imageURL exists
我試圖從另一個內部網站點獲取用戶的縮略圖,但其中一些不遵循預定義的格式,這意味着我想要加載默認縮略圖。
什么是檢查圖像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;
你可以很容易地在jQuery中實現這一點。
$("#myImage")
.load(function() { alert("it loaded ok") })
.error(function() { $(this).attr("src", alternateImage) });
從代碼隱藏檢查
File.Exists(Server.MapPath("file path"))
如果返回true,則分配值,否則分配默認縮略圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.