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