免安裝上傳元件,純 ASP 實作圖片上傳並儲存至 SQL Server image 欄位。包含前端驗證、後端二進位處理、資料庫寫入完整流程。
enctype="multipart/form-data" 表單屬性<input type="file" name="file">.jpg/.gif、大小 ≤ 500KB、解析度 150×130<!-- #include file="../func/conn.inc" -->
<!-- #include file="../func/fupload.inc" --> ' 無元件上傳解析類別
<%
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
Set Fields = GetUpload() ' 解析 multipart/form-data
' 取得文字欄位(二進位轉字串)
strTitle = BinaryToString(Fields("txtTitle").Value)
strSort = BinaryToString(Fields("txtSort").Value)
strContent = BinaryToString(Fields("txtContent").Value)
' 檔案驗證
If InStr(1, LCase(Fields("file").FileName), ".jpg") = 0 And _
InStr(1, LCase(Fields("file").FileName), ".gif") = 0 Then
Response.Write ""
Response.End
End If
If Fields("file").Length > 500000 Then
Response.Write ""
Response.End
End If
' 寫入資料庫
If Fields("file").FileName <> "" Then
Set rs = Server.CreateObject("ADODB.Recordset")
sSql = "SELECT * FROM employee ORDER BY id DESC"
rs.Open sSql, conn, 2, 2 ' adOpenDynamic, adLockPessimistic
If Not rs.EOF Then
iMaxId = CLng(rs("id")) + 1
' ... 後續寫入二進位圖片資料至 image 欄位
End If
End If
End If
%>
fupload.inc 實作 GetUpload() 解析 Request.BinaryRead 原始資料流BinaryToString() 處理欄位值編碼轉換ADODB.Recordset 的 AppendChunk 分塊寫入 image 欄位CREATE TABLE employee (
id INT PRIMARY KEY,
title NVARCHAR(200),
sort NVARCHAR(50),
content NTEXT,
photo IMAGE, -- 儲存二進位圖片
photo_name NVARCHAR(100),
photo_size INT,
create_date DATETIME DEFAULT GETDATE()
)
fupload.inc 需自行實作或參考開源無元件上傳類別
此範例展示純 ASP 實現圖片上傳入庫的完整流程,適合無法安裝元件的虛擬主機環境。