在 Classic ASP 中从 MS-Access 数据库中读取图像

Reading image from MS-Access database in Classic ASP

我正在尝试使用经典 ASP 中的以下代码从 MS-Access 数据库中读取 JPG 图像:

Response.Expires = 0
Response.Buffer = TRUE
Response.Clear

Response.ContentType = "image/jpg"

Set cn = Server.CreateObject("ADODB.Connection")
cn.Open  "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("/database/database.mdb")    

sqlString = "Select * from tblBusinessImages where fldID = " & request.querystring("id")
Set rs = cn.Execute(sqlString)
Response.BinaryWrite rs("fldImageData")
Response.End

但我一直收到错误消息,提示浏览器无法读取或显示图像。

数据库字段'tblBusinessImages'是一个OLE字段,图片是复制粘贴保存的,暂时只做测试(会不会是写错了?)

现在我知道 MS-Access 在 BLOB 对象中保存了额外的数据(正如 MSDN 所说 here

If any extraneous information is contained in the BLOB data, this will be passed by this script, and the image will not display properly. This becomes important when you realize that most methods of placing images into BLOB fields place extra information in the form of headers with the image. Examples of this are Microsoft Access and Microsoft Visual FoxPro. Both of these applications save OLE headers in the BLOB field along with the actual binary data.

)

我的问题是如何在没有 MS-Access 额外保存的 data/headers 的情况下从 BLOB 读取 RAW 图像数据?

谢谢。

经过一天的工作,我发现了问题所在:问题出在将图片保存到数据库(手动)的方式上。

为了将图像保存到数据库,应使用以下代码:

Dim fileName
Dim conn
Dim rsTemp
Dim fldID
Dim sSQL
Dim mystream

Set mystream = Server.CreateObject("ADODB.Stream")
mystream.Type = 1
mystream.Open
mystream.LoadFromFile  "D:\Desktop\My Downloads\compose1.jpg"

Set conn = Server.CreateObject("ADODB.Connection")
Set rsTemp = Server.CreateObject("ADODB.Recordset")

conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("/database/database.mdb")
sSQL = "Select fldImageData from tblBusinessImages where fldID = 1;"

rsTemp.Open sSQL, conn, 3, 3

rsTemp.Fields("fldImageData").AppendChunk mystream.Read

rsTemp.Update
rsTemp.Close
set mystream = nothing

为了从 MS-Access 数据库中读取图像,应该使用以下代码:

Dim conn
Dim rsTemp
Dim sSQL
Dim fldID

fldID = Request.QueryString("id")

If Not fldID = "" And IsNumeric(fldID) Then

    Set conn = Server.CreateObject("ADODB.Connection")
    Set rsTemp = Server.CreateObject("ADODB.Recordset")

    conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("/database/database.mdb")

    sSQL = "Select * from tblBusinessImages where fldID = " & request.querystring("id")

    rsTemp.Open sSQL, conn, 3, 3

    If Not rsTemp.EOF Then
        Response.ContentType = "image/jpeg"
        Response.BinaryWrite rsTemp("fldImageData")
    Else
        Response.Write("File could not be found")
    End If

    rsTemp.Close
    conn.Close

    Set rsTemp = Nothing
    Set conn = Nothing
Else
    Response.Write("File could not be found")
End If

这样图像数据将在数据库的OLE字段中保存为Long Binary Data。阅读时,它将作为可读图像数据发布到浏览器。