ASP上传功能的实例分析
<%@ Language=VBScript %>
<% option explicit %>
<html>
<head>
<title>显示数据库中已有图片的列表</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>
4、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
%>
上面讲了单个图片文件保存到数据库,下面讲一下文本信息与图片文件同时提交保存到数据库,图片文件也可保存到磁盘文件。
MultiInputOrImageToData.asp
<%@ Language=VBScript %>
<% option explicit %>
<%
'把一段二进制数据写入到一个文件
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 '如果该文件已经存在,无条件覆盖
srmObj.Close
set srmObj = nothing
end sub
'二进制数据转换为字符串,包括汉字
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 '位置计数首数不一样,这个对象是对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
'双字节字符串转换成单字节字符串
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