ASP下通过Adodb.Stream实现多线程下载大文件(文件名.asp)全程干货

随心笔谈12个月前发布 admin
99 0


option explicit

‘inputFile 需要下载的文件
‘outputName 输出文件名,可以为空,为空时自动根据 inputFile 生成
Sub CreateDownloader(byval inputFile, byval outputName)
Dim filePath
filePath=Server.Mappath(inputFile)
If outputName=”” Then outputName=Split(filePath, “”)(UBound(Split(filePath, “”)))

‘下载开始
Dim AdoStream, bufferSize
Set AdoStream=Server.CreateObject(“Adodb.Stream”) ‘Adodb.Stream,实例变量名为了方便区分用大写
bufferSize=2 * 1024 * 1024 ‘每次读取大小(byte) 2M
AdoStream.Mode=3 ‘1 读,2 写,3 读写
AdoStream.Type=1 ‘1 二进制,2 文本
AdoStream.Open
AdoStream.LoadFromFile(filePath) ‘载入文件
Response.AddHeader “Content-Disposition”, “attachment; filename=” & outputName ‘文件名
Response.ContentType=”application/octet-stream” ‘通知浏览器接受的文件类型(可自己定义,很多种,但一般都用这个

Dim httpRange,rangeStart,fileSize
‘获取 分段下载 请求
httpRange=Request.ServerVariables(“HTTP_RANGE”)
fileSize=AdoStream.size ‘文件总大小

If httpRange=”” Then
‘不支持断点续传
rangeStart=0
Else
‘支持断点续传
httpRange=Mid(httpRange, 7)
rangeStart=CLng(Split(httpRange, “-“)(0))

If rangeStart < 0 Or rangeStart >=fileSize Then
‘已经下载完毕
Response.Status=”416 Requested range not satisfiable”
Else
Response.Status=”206 Partial Content”
Response.AddHeader “Content-Range”, “bytes ” & rangeStart & “-” & (fileSize – 1) & “/” & fileSize
AdoStream.Position=rangeStart
End If

End If

Dim binaryBlock

If Response.Status <> “416 Requested range not satisfiable” Then
Response.AddHeader “Content-Length”, fileSize – rangeStart ‘通知浏览器接收的文件大小
binaryBlock=AdoStream.Read(bufferSize)

Do While Lenb(binaryBlock) > 0 ‘循环读取直到读完为止
Response.BinaryWrite binaryBlock ‘输出二进制数据流
Response.Flush ‘立即发送(要求至少256字节),不加的话可能提示超过缓存区。
binaryBlock=AdoStream.Read(bufferSize)
Loop

End If

AdoStream.Close ‘关闭文件对象
Set AdoStream=Nothing
Response.End
End Sub

© 版权声明

相关文章