首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

ASP 無元件上傳圖片至 SQL Server 資料庫完整實作範例

     編輯:關於SqlServer

免安裝上傳元件,純 ASP 實作圖片上傳並儲存至 SQL Server image 欄位。包含前端驗證、後端二進位處理、資料庫寫入完整流程。

前端頁面 (addemployee.asp) 重點

  • enctype="multipart/form-data" 表單屬性
  • 檔案輸入:<input type="file" name="file">
  • JavaScript 驗證:副檔名限定 .jpg/.gif、大小 ≤ 500KB、解析度 150×130

後端處理 (transact1.asp) 核心邏輯

<!-- #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
%>

關鍵技術點

  1. 無元件上傳解析: fupload.inc 實作 GetUpload() 解析 Request.BinaryRead 原始資料流
  2. 二進位轉字串: BinaryToString() 處理欄位值編碼轉換
  3. 圖片儲存: 使用 ADODB.Recordset 的 AppendChunk 分塊寫入 image 欄位
  4. 主鍵產生: 查詢最大 ID + 1(生產環境建議用 Identity/Sequence)

完整資料表結構建議

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()
)

注意事項

  • 大量/大檔案上傳建議改用元件或 .NET 處理,避免 ASP 記憶體壓力
  • 生產環境應加入交易控制、錯誤處理、SQL 參數化防注入
  • fupload.inc 需自行實作或參考開源無元件上傳類別

此範例展示純 ASP 實現圖片上傳入庫的完整流程,適合無法安裝元件的虛擬主機環境。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved