首页 > 解决方案 > FileExists 返回 False

问题描述

我正在创建一个经典 ASP 页面并尝试确定 .jpg 是否在我的 Web 服务器上。如果图像存在,那么我想使用它,但如果图像不存在,我会显示一个通用图像。这总是错误的。有任何想法吗?

<%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%>

标签: vbscriptasp-classic

解决方案


仅支持从文件系统访问文件,Scripting.FileSystemObject无法确定文件是否存在于特定的外部 URL。如果 URL 在您可以使用的当前 Web 应用程序中;

Server.MapPath(relative_path)

如果传递了相对服务器路径"/photos",即将返回服务器上文件的物理路径,然后您可以使用fs.FileExists().

但是,如果 URL 是外部的,您仍然可以选择。通过对 URL 使用服务器端XHR请求并根据响应确定它的存在。我们还可以通过只询问它是否存在而不返回内容来提高效率,我们可以通过使用HEAD请求来做到这一点。

这是一个可能的实现示例;

<%
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
%>

输出:

File Exists

有用的链接


推荐阅读