Asp.net check if imageURL exists

I am trying to get a user's thumbnail from another intranet site, but some of them do not match the predefined format, which means that I want to download the default thumbnail.

What is the best way to check if the image URL is valid?

+6
source share
4 answers

Depending on how you get the images, this may change.

<html> <body> <img src="<dynamic handler url>" alt="My Username" onError="this.src='defaultProfile.jpg';" /> </body> </html> 

Here's how you do it in ASP.NET.

Designer -

 <asp:Image ImageUrl="NonexistentImage.Jpg" ID="profileImage" Height="50" Width="50" runat=server /> 

Code for (C #)

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

This works great for me.

+9
source
 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; 
+2
source

You can easily achieve this in jQuery.

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

From code verification

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

If it returns true, set the value, otherwise set the default thumbnail.

0
source

Source: https://habr.com/ru/post/916984/


All Articles