萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 列出目錄所有檔案:FileSystemObject 完整實作與安全防護

核心物件:Scripting.FileSystemObject

FSO 提供完整的檔案系統操作能力,列出目錄檔案是基礎應用。

方法一:列出指定虛擬路徑下所有檔案

<%
Dim fso, folder, files, file, virtualPath, physicalPath
virtualPath = "/uploads/documents/" ' 相對網站根目錄
physicalPath = Server.MapPath(virtualPath)

Set fso = Server.CreateObject("Scripting.FileSystemObject")

If fso.FolderExists(physicalPath) Then
    Set folder = fso.GetFolder(physicalPath)
    Set files = folder.Files
    
    Response.Write "
    " For Each file In files Response.Write "
  • " Response.Write "" Response.Write Server.HTMLEncode(file.Name) Response.Write " " Response.Write "(" & FormatFileSize(file.Size) & ")" Response.Write " - 建立: " & file.DateCreated Response.Write " - 修改: " & file.DateLastModified Response.Write "
  • " Next Response.Write "
" Else Response.Write "目錄不存在: " & Server.HTMLEncode(physicalPath) End If Set folder = Nothing Set fso = Nothing Function FormatFileSize(bytes) If bytes < 1024 Then FormatFileSize = bytes & " bytes" ElseIf bytes < 1024 * 1024 Then FormatFileSize = Round(bytes / 1024, 1) & " KB" Else FormatFileSize = Round(bytes / (1024 * 1024), 2) & " MB" End If End Function %>

方法二:遞迴列出所有子目錄與檔案 (樹狀)

<%
Function ListFolderTree(folderPath, level)
    Dim fso, folder, subFolder, file, indent
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(folderPath)
    indent = String(level * 2, " ")
    
    Response.Write indent & "📁 " & Server.HTMLEncode(folder.Name) & "<br/>"
    
    For Each file In folder.Files
        Response.Write indent & "  📄 " & Server.HTMLEncode(file.Name) & " (" & FormatFileSize(file.Size) & ")<br/>"
    Next
    
    For Each subFolder In folder.SubFolders
        ListFolderTree subFolder.Path, level + 1
    Next
End Function

' 使用
ListFolderTree Server.MapPath("/uploads"), 0
%>

方法三:依副檔名過濾 (如僅列圖片)

<%
Dim allowedExt, ext, file
allowedExt = Array("jpg", "jpeg", "png", "gif", "bmp", "webp")

For Each file In files
    ext = LCase(fso.GetExtensionName(file.Name))
    If IsInArray(ext, allowedExt) Then
        ' 輸出圖片縮圖連結
        Response.Write ""
        Response.Write ""
        Response.Write ""
    End If
Next

Function IsInArray(val, arr)
    Dim i
    For i = 0 To UBound(arr)
        If arr(i) = val Then IsInArray = True : Exit Function
    Next
    IsInArray = False
End Function
%>

安全防護關鍵 (必讀)

  1. 路徑遍歷防護:絕不直接使用 `Request("path")` 做 `Server.MapPath`
    ' ❌ 危險
    physicalPath = Server.MapPath(Request("folder"))
    
    ' ✅ 安全:白名單驗證或固定基礎路徑
    basePath = Server.MapPath("/uploads/")
    requestedPath = Server.MapPath("/uploads/" & Request("folder"))
    ' 確保 requestedPath 以 basePath 開頭
    If InStr(requestedPath, basePath) <> 1 Then Response.End
    
  2. 執行權限移除:IIS 管理器 → 上傳目錄 → Handler Mappings → 移除 `StaticFile` 以外的腳本處理器
  3. 檔案類型驗證:上傳時驗證 MIME、副檔名、檔頭 Magic Number,非圖片不執行
  4. 資訊洩露:不要列出系統目錄、設定檔、資料庫檔 (.mdb, .config, .log)

進階:JSON API 供前端 AJAX 使用

<%
Response.ContentType = "application/json; charset=UTF-8"
Dim fso, folder, files, file, json, first
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(Server.MapPath("/api/files/"))
Set files = folder.Files

json = "{""files"":["
first = True
For Each file In files
    If Not first Then json = json & ","
    first = False
    json = json & "{""name"":""" & EscapeJSON(file.Name) & """,""size"":" & file.Size & ",""modified"":""" & file.DateLastModified & """}"
Next
json = json & "]}"
Response.Write json

Function EscapeJSON(str)
    str = Replace(str, "\", "\\")
    str = Replace(str, """", "\""")
    str = Replace(str, vbCrLf, "\n")
    str = Replace(str, vbCr, "\n")
    str = Replace(str, vbLf, "\n")
    EscapeJSON = str
End Function
%>

善用 FSO 列舉檔案,配合嚴格路徑驗證與權限控制,可構建安全的檔案管理、圖庫瀏覽、API 介面等功能。

copyright © 萬盛學電腦網 all rights reserved