文件下载函数

来源:互联网 发布:知乎人生赢家标准 编辑:程序博客网 时间:2024/06/07 03:11

<%
Function DownloadFile(s_DownFilePath,USE_STREAM,ALLOW_FILE_EXT)
If IsNull(s_DownFilePath) = True Or Trim(s_DownFilePath) = "" Then
OutputErr "错误:先确定要下载的文件,下载失败"
End If
Dim s_FileExt
s_FileExt = Mid(s_DownFilePath, InstrRev(s_DownFilePath, ".")+1)
If InStr("," & ALLOW_FILE_EXT & ",", "," & s_FileExt & ",") <= 0 Then
OutputErr "错误:文件类型(" & s_FileExt & ")不允许被下载,下载失败"
End If
s_DownFilePath = Replace(s_DownFilePath, "", "/")
Dim o_Fso
'On Error Resume Next
Set o_Fso = Server.CreateObject("Scripting.FileSystemObject")
If Err.Number <> 0 Then
Err.Clear
OutputErr "错误:服务器不支持fso组件,下载失败"
End If
Dim s_FileMapPath
Dim o_File, s_FileName, n_FileLength
s_FileMapPath = Server.MapPath(s_DownFilePath)
If (o_Fso.FileExists(s_FileMapPath)) = True Then
Set o_File = o_Fso.GetFile(s_FileMapPath)
s_FileName = o_File.Name
n_FileLength = o_File.Size
'o_File.Close
Else
OutputErr "错误:文件不存在,下载失败"
End If
Set o_Fso = Nothing
If USE_STREAM = 0 Then
Response.Redirect sDownFilePath
Response.end
End If

'On Error Resume Next
Set o_Stream = Server.CreateObject("Adodb.Stream")
If Err.Number <> 0 Then
Err.Clear
OutputErr "错误:服务器不支持Adodb.Stream组件,下载失败"
End If
o_Stream.Type = 1
o_Stream.Open
o_Stream.LoadFromFile s_FileMapPath
Response.Buffer = True
Response.Clear
Response.AddHeader "Content-Disposition", "attachment; filename=" & s_FileName
Response.AddHeader "Content-Length", n_FileLength
'Response.CharSet = "UTF-8"
'Response.ContentType = "application/octet-stream"
Response.ContentType = "application/vnd.ms-word"

readfile=replace(readfile,"{%name%}","张三")
readfile=replace(readfile,"{%sex%}","男")
readfile=replace(readfile,"{%xueli%}","大专")

Response.BinaryWrite o_Stream.Read
Response.Flush

o_Stream.Close
Set o_Stream = Nothing
End Function

Sub OutputErr(s_ErrMsg)
Response.Write "<font color=red>" & s_ErrMsg & "</font>"
Response.End
End Sub

dim use_stream
USE_STREAM = 1 '0.不用流(Adodb.Stream)下载 1.用流下载
dim allow_file_ext
ALLOW_FILE_EXT = "rar,zip,chm,doc,xls,swf,mp3,gif,jpg,jpeg,png,bmp"
Dim sDownFilePath
sDownFilePath = "wordmb/n2006-09-01.doc"
Call DownloadFile(sDownFilePath,USE_STREAM,ALLOW_FILE_EXT)
%>