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

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

url=wscript.arguments(0)                           '参数数组下标从0开始'
if url="" then die("URL can't be null.")               '敢唬我,空url可不行'
if wscript.arguments.count>1 then                     '先判断参数个数是否大于1'
  filename=wscript.arguments(1)                     '再访问第二个参数'
else                                       '如果没有给出文件名,就从url中获得'
  t=instrrev(url,"/")                           '获得最后一个"/"的位置'
  if t=0 or t=len(url) then die("Can not get filename to save.")   '没有"/"或以"/"结尾'
  filename=right(url,len(url)-t)                     '获得要保存的文件名'
end if
if not left(url,7)="http://" then url="http://"&url         '如果粗心把“http://”忘了,加上'

set fso=wscript.createobject("Scripting.FileSystemObject")   'FSO,ASO,HTTP三个对象一个都不能少'
set aso=wscript.createobject("ADODB.Stream")
set http=wscript.createobject("Microsoft.XMLHTTP")

if fso.fileexists(filename) then                     '判断要下载的文件是否已经存在'
  start=fso.getfile(filename).size                   '存在,以当前文件大小作为开始位置'
else
  start=0                                   '不存在,一切从零开始'
  fso.createtextfile(filename).close                 '新建文件'
end if

wscript.stdout.write "Connectting..."                 '好戏刚刚开始'
current=start                                 '当前位置即开始位置'
do
  http.open "GET",url,true                         '这里用异步方式调用HTTP'
  http.setrequestheader "Range","bytes="&start&"-"&cstr(start+20480) '断点续传的奥秘就在这里'
  http.setrequestheader "Content-Type:","application/octet-stream"
  http.send                                   '构造完数据包就开始发送'

  for i=1 to 120                               '循环等待'
    if http.readystate=3 then showplan()               '状态3表示开始接收数据,显示进度'
    if http.readystate=4 then exit for               '状态4表示数据接受完成'
    wscript.sleep 500                           '等待500ms'
  next
  if not http.readystate=4 then die("Timeout.")           '1分钟还没下完20k?超时!'
  if http.status>299 then die("Error: "&http.status&" "&http.statustext) '不是吧,又出错?'
  if not http.status=206 then die("Server Not Support Partial Content.") '服务器不支持断点续传'