深入挖掘Windows脚本技术第1/2页

2019-01-15 14:49:28王旭

  aso.type=1                                 '数据流类型设为字节'
  aso.open
  aso.loadfromfile filename                       '打开文件'
  aso.position=start                             '设置文件指针初始位置'
  aso.write http.responsebody                       '写入数据'
  aso.savetofile filename,2                       '覆盖保存'
  aso.close

  range=http.getresponseheader("Content-Range")           '获得http头中的"Content-Range"'
  if range="" then die("Can not get range.")             '没有它就不知道下载完了没有'
  temp=mid(range,instr(range,"-")+1)                 'Content-Range是类似123-456/789的样子'
  current=clng(left(temp,instr(temp,"/")-1))             '123是开始位置,456是结束位置'
  total=clng(mid(temp,instr(temp,"/")+1))               '789是文件总字节数'
  if total-current=1 then exit do                   '结束位置比总大小少1就表示传输完成了'
  start=start+20480                             '否则再下载20k'
loop while true

wscript.echo chr(13)&"Download ("&total&") Done."         '下载完了,显示总字节数'

function die(msg)                               '函数名来自Perl内置函数die'
wscript.echo msg                               '交代遗言^_^'
wscript.quit                                   '去见马克思了'
end function

function showplan()                             '显示下载进度'
if i mod 3 = 0 then c="/"                         '简单的动态效果'
if i mod 3 = 1 then c="-"
if i mod 3 = 2 then c=""
wscript.stdout.write chr(13)&"Download ("¤t&") "&c&chr(8)'13号ASCII码是回到行首,8号是退格'
end function

可以看到,http控件的功能是很强大的。通过对http头的操作,很容易就实现断点续传。例子中只是单线程的,事实上由于http控件支持异步调用和事件,也可以实现多线程下载。在MSDN里有详细的用法。至于断点续传的详细资料,请看RFC2616。