Search code examples
vbscriptasp-classic

FileExists Returning False


I'm creating a Classic ASP page and trying to determine if a .jpg is on my web server. If the image exists then I want to use it, but if the image does not exist, I display a generic image. This is always false. Any ideas?

<%dim fs
strFilePath =("http:/example.com/photos/" & PersonID & ".jpg")
set fs=Server.CreateObject("Scripting.FileSystemObject")

  if fs.FileExists(strFilePath) then
     response.write "<img src='../photos/"& PersonID &".jpg'"&">"
 else%>
     <img src="http://exmaple.com/images/nophoto.jpg">
<%end if

set fs=nothing%>

Solution

  • The Scripting.FileSystemObject only supports accessing files from the file system and has no way to determine whether a file exists at a particular external URL. If the URL is within the current Web Application you can use;

    Server.MapPath(relative_path)
    

    which if passed a relative server path i.e "/photos" will return the physical path to the file on the server, which you can then test with fs.FileExists().

    But if the URL is external you still have options. By using a server-side XHR request to the URL and based on the response, determine it's existence. We can also make this more efficient by only asking whether it is there and not returning the content, which we can do by using a HEAD request.

    Here is an example of a possible implementation;

    <%
    Function CheckFileExists(url)
      Dim xhr: Set xhr = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
      With xhr
        Call .Open("HEAD", url)
        Call .Send()
        CheckFileExists = (.Status = 200)
      End With
    End Function
    
    If CheckFileExists("https://cdn.sstatic.net/Img/unified/sprites.svg?v=fcc0ea44ba27") Then
      Call Response.Write("File Exists")
    Else
      Call Response.Write("File Doesn't Exist")
    End If
    %>
    

    Output:

    File Exists
    

    Useful Links