FileExists返回错误的[重复项]

问题描述 投票:-2回答:1

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

<%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%>
vbscript asp-classic
1个回答
0
投票

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

有用的链接

© www.soinside.com 2019 - 2024. All rights reserved.