在經典 ASP 開發中,檔案上傳是常見需求。為了防止使用者上傳過大的檔案佔用伺服器資源,必須在伺服端進行檔案大小驗證。本文示範如何使用 upload_5xsoft 元件,在檔案寫入磁碟前攔截並限制上傳檔案大小。
元件會將上傳的二進位資料解析為檔案集合,我們可以遍歷 upload.file 集合,取得每個檔案物件的 filesize 屬性(單位為 Byte)。若超過設定閾值(例如 1,000,000 Byte ≈ 1000 KB),即中止儲存並回傳錯誤訊息。
<%
Dim upload, file, formName, formPath, iCount, fileName, fileExt
Set upload = New upload_5xsoft ' 建立上傳物件
formPath = "download/" ' 儲存目錄,結尾需加 "/"
If Right(formPath, 1) <> "/" Then formPath = formPath & "/"
For Each formName In upload.file ' 列出所有上傳檔案
Set file = upload.file(formName) ' 取得單一檔案物件
' === 檔案大小驗證 (1,000,000 Byte = 約 1000 KB) ===
If file.filesize > 1000000 Then
message = 1 ' 超過大小限制
Else
' === 副檔名驗證 ===
fileExt = LCase(Right(file.filename, 4))
If fileExt <> ".exe" And fileExt <> ".zip" And fileExt <> ".rar" And fileExt <> ".mxp" Then
message = 2 ' 檔案類型不允許
Else
' 產生唯一檔名:lemongtree_YYYYMMDDHHMMSS_隨機數.副檔名
Randomize
Dim ranNum : ranNum = Int(90000 * Rnd) + 10000
fileName = formPath & "lemongtree_" & Year(Now) & Month(Now) & Day(Now) _
& Hour(Now) & Minute(Now) & Second(Now) & ranNum & fileExt
file.SaveAs Server.MapPath(fileName) ' 儲存檔案
' 記錄檔案類型與大小 (KB)
Select Case fileExt
Case ".zip" : uploadType = "zip"
Case ".rar" : uploadType = "rar"
Case ".mxp" : uploadType = "mxp"
Case ".exe" : uploadType = "exe"
End Select
uploadChar = fileName
size = CLng(file.filesize) / 1000
message = 3 ' 上傳成功
End If
End If
Next
%>
<% If message = 1 Then %> ' 大小超標
<html><head><title>大小超標</title>
<script>function error_size(){alert("檔案大小超過 1000KB,請重新選擇。");window.location="upload.asp";}</script></head>
<body onload="error_size()"></body></html>
<% ElseIf message = 2 Then %> ' 類型不符
<html><head><title>類型不匹配</title>
<script>function error_type(){alert("只能上傳 zip / rar / exe / mxp 檔案!");window.location="upload.asp";}</script></head>
<body onload="error_type()"></body></html>
<% ElseIf message = 3 Then %> ' 成功
<html><head><title>上傳成功</title>
<script>function image_success(){alert("檔案上傳成功!");parent.form1.url1.value="<%=uploadChar%>";parent.form1.size.value="<%=size%>k";window.location="upload.asp";}</script></head>
<body onload="image_success()"></body></html>
<% End If %>
<%
Set file = Nothing
Set upload = Nothing
%>
message 變數導向不同的回應頁面,並以 JavaScript 彈窗提示使用者。此範例適用於仍在維護經典 ASP 系統、需快速加入檔案大小與類型限制的專案。若為新專案,建議改用 ASP.NET Core 或其他現代框架,內建更完整的上傳驗證機制。