asp学习网: 首页 >> asp对象 >> response/request >> ASP通过response修改HTTP头部信息实现文件直接下载

ASP通过response修改HTTP头部信息实现文件直接下载

'定义所有需要使用的变量
Dim strFilename,S,Fso,F,intFilelength
strFilename = Server.MapPath(Trim(Request("File")))
Response.Buffer = True
Response.Clear
Set S = Server.CreateObject("ADODB.Stream")
S.Open
S.Type = 1
On Error Resume Next
Set Fso = Server.CreateObject("Scripting.FileSystemObject")
If Not Fso.FileExists(strFilename) Then
Response.Write("<h1>Error:</h1>"&strFilename&"你要下载的文件不存在!<p>")
Response.End
End If

Set F = Fso.GetFile(strFilename)
intFilelength = F.Size '获取文件大小
S.LoadFromFile(strFilename)
If Err Then
Response.Write("<h1>Error: </h1>Unknown Error!<p>")
Response.End
End If

Response.AddHeader "Content-Disposition","attachment;filename="&F.name
Response.AddHeader "Content-Length",intFilelength
Response.CharSet = "GB2312"
Response.ContentType = "application/octet-stream"
Response.BinaryWrite S.Read
Response.Flush

 

这里添加一点说明,通过修改头部信息可以让浏览器知道是需要下载文件,另外上面的代码可以修改一下,

with response

end with就可以了 www.aspxuexi.com  asp学习网整理
S.Close
Set S = Nothing


对文本类文件(*.txt;*.html;*.doc;等等),图片类文件(*.jpg;*.gif等等)直接点击链接时会在浏览器打开,而无法出现下载保存对话框。
如果要实现点击上述文件,弹出保存对话框,则需要用到下面这个函数了:

程序代码
<%
'Call downloadFile(Request("path"))

function downloadFile(strFile)
strFilename = server.MapPath(strFile)

'Clear the buffer
Response.Buffer = True
Response.Clear

'Create stream
Set s = Server.CreateObject("ADODB.Stream")
s.Open

'Set as binary
s.Type = 1

'Load in the file
on error resume next

'Check the file exists
Set fso = Server.CreateObject("Scripting.FileSystemObject")
if not fso.FileExists(strFilename) then
Response.Write("<p><strong>Error: </strong>" & strFilename & " does not exist</p>")
Response.End
end if

'Get length of file
Set f = fso.GetFile(strFilename)
intFilelength = f.size

s.LoadFromFile(strFilename)
if err then
Response.Write("<p><strong>Error: </strong>" & err.Description & "</p>")
Response.End
end if

'Send the headers to the users browser
Response.AddHeader "Content-Disposition", "attachment; filename=" & f.name
Response.AddHeader "Content-Length", intFilelength
Response.CharSet = "UTF-8"
Response.ContentType = "application/octet-stream"

'Output the file to the browser
Response.BinaryWrite s.Read
Response.Flush

'Tidy up
s.Close
Set s = Nothing

End Function
%>

from:asp学习网/title:ASP通过response修改HTTP头部信息实现文件直接下载/ time:2007-2-1 23:18:15

本文主题ASP通过response修改HTTP头部信息实现文件直接下载

asp教程 ©2006-2007 aspxuexi.com | 关于站点 | 版权隐私 | 站内搜索
复制或者翻版 请于夜间进行