|          
在 SQL Server 當中有一款資料類型號作 Image , 除了可以儲存圖檔外它還可以儲存大型的二進位資料檔, 對這一個欄位大部分的人是聽過但是不知影按怎來用, 今日的文章就要來討論如何將圖檔存入去資料庫 
 準備工作
 
 為了降低這篇文章的篇幅及複雜度, 咱決定借用 Upload 元件來替我們完成檔案上傳的工作, 所要使用的是 Dundas 所提供免錢的上傳元件, 請到下底的網址下載 Dundas Upload 元件並安裝
 
 http://www.dundas.com/
 創造資料表
 
 在這個例咱要用到 SQL 內建的 Pubs 資料庫來作測試, 請打開 QA 然後執行下底的創造資料表指令, 所要建立的資料表中一個欄位是紀錄檔案的 Content-Type, 另一個則是儲存圖檔
 
 Use Pubs
 Create Table ImgData
 (
 ImgID Int Identity Not Null Primary Key,
 ContentType VarChar(20),
 FileData Image
 )
 
 HTML 表單部分
 
 現在來看看 HTML 表單的部分, 因為是用做檔案上傳因此用 enctype="multipart/form-data" , 不過要注意的是一但使用了 form-data 後表單資料的取得也就不能再用 Request.Form, 因為這不是這篇文章的重點所以在這就不多做解釋, 請將下底的碼存成 insert.htm
 
 <html>
 <head>
 <title>資料庫存入圖檔</title>
 </head>
 <body>
 <form method="POST" enctype="multipart/form-data" action="Insert.asp">
 <table border="0" align="center">
 <tr>
 <td>File :</td>
 <td><input type="file" name="file" size="40"></td>
 </tr>
 <tr>
 <td></td>
 <td><input type="submit" value=" 進行上傳 "></td>
 </tr>
 
 </form>
 </body>
 </html>
 
 程式碼
 
 擱來看麥 ASP 的部分, 請將下底的碼存成 insert.asp
 
 <%
 Response.Buffer = True
 ConnStr = "Provider=SQLOLEDB;" _
 & "Data Source=你的電腦名稱;" _
 & "Initial Catalog=Pubs;" _
 & "User Id=sa;" _
 & "Password=你的密碼"
 '建立 oUpload 上傳物件
 Set oUpload = Server.CreateObject("Dundas.Upload.2")
 '在使用 oUpload 集合 (Collection) 前, 要先呼叫 Save 或 SaveToMemory 方法
 oUpload.SaveToMemory
 Set oRs = Server.CreateObject("Adodb.Recordset")
 oRs.Open "ImgData", ConnStr, 2, 3
 oRs.AddNew
 '呼叫 oUpload 物件的 ContentType, Binary 屬性, 已取得我們要的資料
 oRs("ContentType").Value = oUpload.Files(0).ContentType
 oRs("FileData").Value = oUpload.Files(0).Binary
 oRs.Update
 oRs.Close
 Set oRs = Nothing
 %>
 
 頂高的程式假設你只上傳一個檔案, 所以使用 oUpload.Files(0), 如果你一次上傳一個以上的檔案, 你可以將程式小改為
 
 ...
 oRs.Open ...
 For Each oFile In oUpload.Files
 If InStr(1,oFile.ContentType,"image") <> 0 Then
 oRs.AddNew
 oRs("ContentType").Value = oFile.ContentType
 oRs("imgdata").Value = oFile.Binary
 End If
 Next
 oRs.Update
 ...
 
 現在你可以利用瀏覽器開啟 Insert.htm 來進行上傳圖檔到資料庫的動作, 執行完後你可以 Select ImgData 資料表, 應該是出現一筆資料, 不過 FileData 欄位應該是看不懂的啦!
 
 今日的文章就先介紹到這, 下一篇文章再來介紹如何將圖檔從資料庫中拉出來!
 
 希望這篇文章對你有幫助!
 
 
 |