範例包含兩部分:
upload.inc:純 VBScript 實作的 upload_5xSoft 類別,解析 multipart/form-data 二進位資料流,不需安裝 COM 元件。<!--#include FILE="upload.inc"-->
<%
Dim upload, file, formName, formPath, iCount, fileName, fileExt
Set upload = New upload_5xSoft
formPath = "uploadimages/"
If Right(formPath, 1) <> "/" Then formPath = formPath & "/"
iCount = 0
For Each formName In upload.file
Set file = upload.file(formName)
' 檔案大小驗證
If file.filesize < 100 Then
Response.Write "請先選擇圖片"
Response.End
End If
If file.filesize > 1000000 Then
Response.Write "圖片大小超過限制"
Response.End
End If
' 副檔名驗證
fileExt = LCase(Right(file.filename, 4))
If fileExt <> ".jpg" And fileExt <> ".gif" Then
Response.Write "僅允許 jpg/gif 格式"
Response.End
End If
' 產生唯一檔名
Randomize
Dim ranNum : ranNum = Int(90000 * Rnd) + 10000
fileName = formPath & Year(Now) & Month(Now) & Day(Now) _
& Hour(Now) & Minute(Now) & Second(Now) & fileExt
If file.FileSize > 0 Then
file.SaveAs Server.MapPath(fileName)
Response.Write ""
iCount = iCount + 1
End If
Set file = Nothing
Next
Set upload = Nothing
Response.Write "
"
Response.End
%>
Class_Initialize:讀取 Request.BinaryRead(Request.TotalBytes) 到 ADODB.Stream,解析分隔字串、表單欄位、檔案標頭、檔案內容位移與大小。Scripting.Dictionary 儲存表單欄位 (Form) 與檔案資訊 (File)。FileInfo 類別(程式碼中未完整顯示)封裝 FileName、FilePath、FileSize、FileStart(二進位流起始位置)、FormName。SaveAs 方法(隱含於 FileInfo)根據 FileStart、FileSize 從 Stream 切出二進位資料寫入檔案。Class_Terminate 釋放 Stream、Dictionary 物件。| 優點 | 缺點 |
|---|---|
| 純 ASP 程式碼,免註冊 COM 元件 | 解析大檔案效能較差,記憶體佔用高 |
| 原始碼可見,易於客製化 | 未支援大檔案分塊上傳、斷點續傳 |
| 相容舊版 IIS | 未內建防禦惡意檔案內容(需自行掃毒) |
新專案建議改用 ASP.NET Core IFormFile、Node.js multer、PHP $_FILES 等成熟框架功能,或採用雲端儲存直傳(預簽名 URL)降低伺服器負載。