欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP实现文件直接下载的代码

程序员文章站 2022-10-27 19:09:57
<%@ language=vbscript codepage=65001%> <% 'filename must be input if request(...
<%@ language=vbscript codepage=65001%>
<%
'filename must be input
if request("filename")="" then
response.write "<h1>error:</h1>filename is empty!<p>"
else
call downloadfile(replace(replace(request("filename"),"\",""),"/",""))

function downloadfile(strfile)
' make sure you are on the latest mdac version for this to work
' get full path of specified file
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("<h1>error:</h1>"&strfilename&" does not exists!<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("<h1>error: </h1>unknown error!<p>")
response.end
end if
' send the headers to the users browse
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
end if
%>