ASP上傳功能的實例分析
<%@ Language=VBScript %>
<% option explicit %>
<html>
<head>
<title>顯示數(shù)據(jù)庫中已有圖片的列表</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<p><a href="SimpleImageToData.asp">上傳圖片</a>
<a href="ShowImageListFromData.asp">顯示圖片</a><hr></p>
<table border=0 cellpadding=2 cellspacing=2>
<tr>
<td valign=top>
<%
dim cnstr
cnstr = "driver={Microsoft Access Driver (*.mdb)};dbq=" & server.MapPath("./upload.mdb")
dim cn, sql, rs
set cn = server.CreateObject("adodb.connection")
cn.Open cnstr
sql = "select sn,[content-type],image from tblImage"
set rs = cn.Execute(sql)
response.Write "<table border=1 cellspacing=2 cellpadding=5>"
response.Write "<tr>"
response.Write "<th>序列號</th><th>圖片類型</th><th>圖片</th>"
response.Write "</tr>"
do until rs.eof
response.Write "<tr>"
response.Write "<td>" & rs("sn") & "</td>"
response.Write "<td>" & rs("content-type") & "</td>"
response.Write "<td><a href='ShowImageListFromData.asp?sn=" & rs("sn") & "'>看圖</a></td>"
response.Write "</tr>"
rs.movenext
loop
response.Write "</table>"
cn.Close
set cn = nothing
%>
</td>
<td valign=top>
<%
dim sn
sn = request.QueryString("sn")
if sn = "" then
response.Write "沒有指定圖片!"
else
response.Write "<img border=1 src=ShowImageFromData.asp?sn=" & sn & ">"
end if
%>
</td>
</tr>
</table>
</body>
</html>
。、ShowImageFromData.asp
<%@ Language=VBScript %>
<% option explicit %>
<%
dim sn
sn = request.QueryString("sn")
if sn = "" then response.End
dim cnstr
cnstr = "driver={Microsoft Access Driver (*.mdb)};dbq=" & server.MapPath("./upload.mdb")
dim cn, sql, rs
set cn = server.CreateObject("adodb.connection")
cn.Open cnstr
sql = "select sn,[content-type],image from tblImage where sn=" & cint(sn)
set rs = cn.Execute(sql)
response.ContentType = rs("content-type")
response.BinaryWrite rs("image")
set rs = nothing
cn.Close
set cn = nothing
%>
上面講了單個圖片文件保存到數(shù)據(jù)庫,下面講一下文本信息與圖片文件同時提交保存到數(shù)據(jù)庫,圖片文件也可保存到磁盤文件。
MultiInputOrImageToData.asp
<%@ Language=VBScript %>
<% option explicit %>
<%
'把一段二進制數(shù)據(jù)寫入到一個文件
sub saveBin2File(srmSource,posB,posLen,strPath)
dim srmObj
set srmObj = server.CreateObject("adodb.stream")
srmObj.Type = 1
srmObj.Mode = 3
srmObj.Open
srmSource.Position = posB-1
srmSource.CopyTo srmObj,posLen
srmObj.Position = 0
srmObj.SaveToFile strPath,2 '如果該文件已經(jīng)存在,無條件覆蓋
srmObj.Close
set srmObj = nothing
end sub
'二進制數(shù)據(jù)轉換為字符串,包括漢字
function getTextfromBin(srmSource,posBegin,posLen)
dim srmObj, strData
set srmObj = server.CreateObject("adodb.stream")
srmObj.Type = 1
srmObj.Mode = 3
srmObj.Open
srmSource.position = posBegin-1 '位置計數(shù)首數(shù)不一樣,這個對象是對0開始的
srmSource.CopyTo srmObj,posLen
srmObj.Position = 0
srmObj.Type = 2
srmObj.Charset = "gb2312"
strData = srmObj.ReadText
srmObj.Close
set srmObj = nothing
getTextfromBin = strData
end function
'雙字節(jié)字符串轉換成單字節(jié)字符串
function getSBfromDB(bytString)
dim bin, i
bin = ""
for i=1 to len(bytString)
bin = bin & chrb(asc(mid(bytString,i,1)))
next
getSBfromDB = bin
end function