现在的位置: 首页 > 综合 > 正文

File Download by ASP Stream文件流下载功能

2013年09月02日 ⁄ 综合 ⁄ 共 1790字 ⁄ 字号 评论关闭

<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>

<%
Dim  fullName, s, fs, fl, Filesize, Filename, currentPath, relativePath

'取得文件名参数,可以是表单提交或者查询字符串
fullName = Request.QueryString("down")
If fullName = "" Then Call ShowMessage("对不起,文件名为空!")

'转为绝对路径
'该门课件的根路径
currentPath = Request.ServerVariables("PATH_TRANSLATED")
currentPath = Replace(currentPath,"script/download.asp","")
'网站子路径,为空代表下载文件直接放在根路径,可以添加子路径如"down/"
relativePath = "stream_db/"
'下载文件的完全路径
Filename = currentPath&relativePath&fullName

'检查文件是否存在
Set fs = Server.CreateObject("Scripting.FileSystemObject")
'If Not fs.FileExists(Filename) Then Call ShowMessage("对不起,指定文件不存在!")

'取得文件大小,单位是字节
Set fl = fs.GetFile(Filename)
Filesize = fl.Size

'销毁FSO对象
Set fl = Nothing
Set fs = Nothing

'清理缓存
Response.Buffer = True
Response.Clear

'创建Stream对象
Set s = Server.CreateObject("ADODB.Stream")
s.Open

'设置为二进制方式
s.Type = 1

'容错
On Error Resume Next

'装载文件
s.LoadFromFile (Filename)
If Err Then Call ShowMessage("装载指定文件出现未知错误!")

'向浏览器输出头部
Response.AddHeader "Content-Disposition", "attachment; filename="&fullName
Response.AddHeader "Content-Length",Filesize
'Response.CharSet="UTF-8"
Response.ContentType = "application/octet-stream"

'分段向浏览器输出文件
Do While Not s.EOS
 Contents = s.Read (4096) '每次读取4096KB
 Response.BinaryWrite Contents
 Response.Flush
Loop

'一次性向浏览器输出文件
'Response.BinaryWrite s.Read
'Response.Flush

'销毁对象
s.Close: Set s = Nothing

'在本页输出提示信息
Sub ShowMessage(msg)
  Response.Write "<br><div align='center'><div style='color:red; font-weight:bold; text-align:center; border:1px solid #CCCCCC; 'background-color:#E8E8E8; padding:4px 2px 2px; width:300px; font-size:12px'>" & msg & "</div></div><br>"
  Response.End
End Sub
%>

</body>
</html>

抱歉!评论已关闭.