ASP File

File 对象的属性、复制移动删除、打开为 TextStream。

Intermediate
Key PointsFile 对象代表一个具体文件:能读属性、改名、复制、删除,也能打开成文本流读写。

属性

PropertyMeaning
Name含扩展名,不含路径
ShortName8.3 格式
Path物理路径
Size字节
Type「文本文档」这类描述
DateCreated
DateLastModified
DateLastAccessed
Attributes0 普通 / 1 只读 / 2 隐藏 / 4 系统 / 32 存档
ParentFolder返回 Folder 对象
Drive返回 Drive 对象

读取属性

ASP
<%
    Dim fso, f
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Set f = fso.GetFile(Server.MapPath("/data/report.pdf"))

    Response.Write "名称:" & f.Name & "<br>"
    Response.Write "路径:" & f.Path & "<br>"
    Response.Write "大小:" & FormatNumber(f.Size / 1024, 1) & " KB<br>"
    Response.Write "类型:" & f.Type & "<br>"
    Response.Write "属性:" & f.Attributes & "<br>"
    Response.Write "只读:" & ((f.Attributes And 1) = 1) & "<br>"
    Response.Write "修改:" & f.DateLastModified

    Set f = Nothing
    Set fso = Nothing
%>
Output
名称:report.pdf
路径:C:\inetpub\wwwroot\data\report.pdf
大小:180.0 KB
类型:PDF 文档
属性:32
只读:False
修改:2026/11/2 17:40:55

Attributes is a bit flag; test with And: (f.Attributes And 1) = 1 means read-only. To set it assign f.Attributes = f.Attributes Or 1 and revert afterwards.

复制、移动、删除

ASP
<%
    ' 复制(第三个参数 True = 覆盖已存在的目标)
    f.Copy Server.MapPath("/backup/report.pdf"), True

    ' 移动(等于改名 + 换目录)
    f.Move Server.MapPath("/archive/report.pdf")

    ' 删除(True = 只读文件也删)
    f.Delete True
%>

Copy's second argument is Overwrite (default False, so an existing target errors). Delete's is Force (default False, so read-only files resist). Both defaults are easy to forget.

打开成文本流

ASP
<%
    Dim ts
    Set ts = f.OpenAsTextStream(1)          ' 1 = 只读
    Response.Write ts.ReadAll
    ts.Close
    Set ts = Nothing
%>

OpenAsTextStream is fso.OpenTextFile(f.Path, mode) without repeating the path. Same caveat for large files: do not ReadAll.

上传文件的处理

ASP
<%
    ' 经典 ASP 没有内置上传,常用第三方组件(如 Persits.Upload)
    ' 或用 ADODB.Stream 手工解析 multipart 请求体

    Dim upload, file
    Set upload = Server.CreateObject("Persits.Upload")
    upload.Save Server.MapPath("/uploads")

    For Each file In upload.Files
        Response.Write file.FileName & " — " & file.Size & " 字节<br>"
    Next
%>
Keep upload directories outside the web root, or at minimum disable script execution there. An attacker uploading an .asp file and requesting it gains code execution — the most common way classic ASP sites are compromised.

安全提醒

  • 文件名不可信 —— ../../x.asp 能写到任意位置
  • 扩展名白名单 —— 只允许 .jpg、.pdf 这类,且校验真实内容
  • 重命名保存 —— 用 GUID 或时间戳做文件名,不用原名

Friends & Partners