vbscript - 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%>
解决方案
仅支持从文件系统访问文件,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
有用的链接
- 文件存在吗?ASP Classic (解释使用
Server.MapPath()
)
推荐阅读
- reactjs - 运行流程:安装给出错误
- mysql - 如何删除所有类型为 y 的行,这些行也包含同一个表中类型为 x 的条目?
- symfony - KnpSnappyBundle - wkhtmltopdf:加载 CSS/图像但不加载脚本
- angularjs - AngularJS表单值未显示
- oracle - oracle 包中每个函数/过程调用的所有函数/过程的列表
- django - DJango api 发送刷新和访问令牌
- java - EnumSet / EnumMap 需要泛化 Set / Map
- javascript - 如果日期在角度 js 中无效,如何使边框变红?
- python - PyQt5可以使用QWebEngineView在后台打印PDF,没有GUI?
- r - 稳健的标准错误:泊松面板回归(pglm,lmtest)