代码如下: 复制代码 代码如下: if (lcase(right(wscript.fullname,11))="wscript.exe") then"判断脚本宿主的名称" die("Script host must be CScript.exe.") "脚本宿主不是CScript,于是就die了" end if
if wscript.arguments.count<1 then"至少要有一个参数" die("Usage: cscript webdl.vbs url [filename]") "麻雀虽小五脏俱全,Usage不能忘" end if
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
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.") "服务器不支持断点续传"
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
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