Check if an image file exists before linking in ASP

Discussion in 'Software' started by be0, May 19, 2008.

  1. be0

    be0 Corporal

    Hello everyone,

    I have two websites. One internal and one external. Now all images are located in an externate website and I want to keep them there. I want to link images to products which are available on the external website. Priort to using the <img src=> I want to check it an image exists. If not I wont to display another image.

    I was successfull in finding some Java script code out there but it always returns no image.

    Here is what I got:

    <script language="javascript">
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("<%=response.write(IMGURL)%>");
    req.AllowAutoRedirect = false; // in case the server is configured to redirect on 404
    try
    {
    // Get response from the server
    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    // check response code
    if(res.StatusCode == HttpStatusCode.OK)
    <%IMGURL=IMGURL%>;
    else
    <%IMGURL = "http://www.hinkleylighting.com/images/products/na.gif"%>;
    }
    catch(WebException ex)
    {
    // Handle DSN error.
    System.Diagnostics.Debug.WriteLine("Name resolution error: " + ex.ToString());
    }
    </script>

    Any ideas?
    Thanks.
     
  2. PC-XT

    PC-XT Master Sergeant

    I don't do ASP, but if <%IMGURL> returns html, you would need to use document.write("<%IMGURL=url>"); otherwise the script wouldn't work. Also, if the url tag used double quotes, you would need to use single quotes, unless they are in the file name, in which case you should use an ASP function to add slashes to the special characters, or choose one kind of quote, and replace each of it's occurances with one after a backslash. If you can open the JavaScript console (not Java Console) you can see if there are any errors like this. (In IE, double-click on the error icon in left side of status bar, some browsers accept this url: "javascript:".)
     
  3. Kodo

    Kodo SNATCHSQUATCH

    That looks remarkably like C# and NOT javascript.. :confused:
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds