ASP下通过Adodb.Stream实现多线程下载大文件

2022-07-28,,,,

有个朋友 做 某种小众音乐交换站的(他们那个行业的昵图网),需要用到付费下载。尝试过 防盗链,不太理想,最终使用了 adodb.stream 读取,直接输出。

解决了 盗版的问题,但是新的问题又来了。adodb.stream 这种方式 电脑还好说,大部分电脑浏览器都支持。移动端 很多 浏览器为了 加速读取,会多线程下载导致 文件无法正常读取。

抓包,发现增加了 http头 http_range。隐约记得 之前读过 王大(王洪影)的 《深入解析 asp核心技术》当中提到asp多线程下载的问题,回家翻出来,最终还就真解决了。

为了 方便调用,直接写成了 一个 函数。没用王大的代码,感觉我自己的更美(自恋中…)。如有有需要的朋友需要,直接拿走即可,代码如下:

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

使用也非常简单,假如上面的代码保存到了 downloader.asp,直接引用即可:

<!--#include file="downloader.asp"-->
<%
  '创建下载
  call createdownloader("down/tools.rar", "")
   
  '创建下载并自定义文件名
  call createdownloader("down/tools.rar", "hello.rar")
%>

有图有真相:

到此这篇关于asp下通过adodb.stream实现多线程下载大文件的文章就介绍到这了,更多相关asp多线程下载大文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《ASP下通过Adodb.Stream实现多线程下载大文件.doc》

下载本文的Word格式文档,以方便收藏与打印。