ASP实现文件直接下载的代码
程序员文章站
2022-05-18 11:09:03
<%@ 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
%>
<%
'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
%>