ASP 讀取儲存在資料庫欄位中的 PDF 原始範例
範例假設如下:
database name: DEMODB
database user id: DEMOUser
database user id: DEMOPassword
table name:MY_PDF_TABLE
field1 : pdfID - varchar , 20 , primary key
field2: pdf_content - blob , 1M
ODBC Name: DEMODB
以下挑重點解說:
(1) SQL 指令:
set rs = conn.Execute("SELECT PDF_CONTENT FROM MY_PDF_TABLE WHERE pdfID='"+pdfID+"'")
(2)asp 部份:
Response.Buffer =true
Response.Clear()
(3)設定 MIME TYPE
下面這行是黨你的內容是 pdf 時所要設定的 mime type ,
所以當你的檔案是其他的格式 , 請修改對應的 mime type
Response.ContentType="application/pdf"
(4)Browser 開啟方式: 強制另存檔案 或是 線上開啟檔案
(a) 如果你希望回應到前端 browser 是要強制另存檔案 請用下面這一行
'Response.AddHeader "Content-Disposition" , "attachmentfilename="+pdfID+".pdf"
(b) 如果你希望回應到前端 browser 是要線上開啟檔案 請用下面這一行
Response.AddHeader "Content-Disposition" , "inlinefilename="+pdfID+".pdf"
(5)傳回檔案的二進位串流
回應前端資料使用 BinaryWrite 把二進位串流傳回
dim pdfSize
pdfSize = rs("PDF_CONTENT").ActualSize
Response.BinaryWrite rs("PDF_CONTENT").getChunk(pdfSize)
(6)這一篇雖然是叫做儲存在資料庫欄位中的 PDF 原始範例
但是如果你的 DB 中放的是其他格式的檔案內容也一樣可以通用 ,
假設你放的是 JPG
那麼請修改上述的
(3) MIME TYPE , 請改為 jpg 的 MIME TYPE--> image/jpeg
(4) 開啟方式的檔案名稱的副檔名 , 請改為 .jpg
以下是完整程式碼 , 有執行過 , 確認沒有問題的程式碼
測試方式
開啟瀏覽器: 輸入 以下網址
http://localhost/demo1/ShowPDF.asp?pdfID=BBB9998804
(假設: Windows Server , IIS ,
你建立一個虛擬目錄為 demo1 ,
資料庫中有一筆紀錄 pdfID 為 : BBB9998804 )
===ShowPDF.asp===
<%@Language="VBScript"%>
<%
Response.Charset="utf-8"
Response.Expires=0
dim pdfID
dim pdfID1
dim pdfID2
pdfID1= Request.Form("pdfID") 'POST - 由 input html 中 form 傳入參數
pdfID2 =Request.QueryString("pdfID") 'GET - 直接輸入參數在網址列
if (pdfID1 <> "" ) then pdfID=pdfID1
if (pdfID2 <> "" ) then pdfID=pdfID2
'DB Operation
dim conn
dim rs
dim haveData
haveData=false
set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = "Provider=MSDASQL.1;Password=DEMOPassword;Persist Security Info=True;User ID=DEMOUser;Data Source=DEMODB"
conn.Open()
set rs = conn.Execute("SELECT PDF_CONTENT FROM MY_PDF_TABLE WHERE pdfID='"+pdfID+"'")
on error resume next
rs.MoveFirst()
do while NOT rs.EOF
haveData = true
Response.Buffer =true
Response.Clear()
Response.ContentType="application/pdf"
'Response.AddHeader "Content-Disposition" , "attachmentfilename="+pdfID+".pdf"
Response.AddHeader "Content-Disposition" , "inlinefilename="+pdfID+".pdf"
dim pdfSize
pdfSize = rs(PDF_CONTENT").ActualSize
Response.BinaryWrite rs("PDF_CONTENT").getChunk(pdfSize)
rs.MoveNext()
loop
if (NOT haveData) then Response.Write "查無資料
"
conn.Close()
%>
沒有留言:
張貼留言