//inet.whttp下载文件
import win.ui;
/*DSG{{*/
var winform = win.form(parent=...; text="inet.whttp 下载文件";right=359;bottom=152 )
winform.add( 
editUrl={ bottom=56;right=266;left=36;multiline=1;top=29;z=1;text="http://www.baidu.com";edge=1;cls="edit" };
progress={ bottom=116;max=100;right=332;left=36;top=96;text="progress";z=4;hide=1;min=0;edge=1;cls="progress" };
button={ bottom=56;right=336;left=274;top=30;z=2;text="下载";cls="button" };
labInfo={ text="文件大小: 0KB";bottom=88;right=331;left=37;top=67;z=3;transparent=1;cls="static" }
)
/*}}*/

import fsys;
import inet.whttp;
import process;

winform.button.oncommand = function(id,event){
	//禁用按钮,避免重复点击
	winform.button.disabled = true;
	
	//创建whttp对象
	var url = winform.editUrl.text;
	var whttp = inet.whttp();
	assert( whttp.beginRequest( url ) ) 
	assert( whttp.send() )
	
	//取得文件长度
	var len = whttp.readHeader("Content-Length:") 
	len = tonumber(len); 
	if(len){
		winform.labInfo.text = "文件大小: " + fsys.formatSize(len);
	}
	else {
		winform.labInfo.text = "文件大小: 未知"
		len = 100000;
	}
	
	//初始化进度条
	winform.progress.min=0;
	winform.progress.max=len;
	winform.progress.pos = 0;
	winform.progress.hide = false;
	
	var 缓冲表 = {}
	for( 下载数据,长度 in whttp.eachRead() ){
		winform.progress.pos += 长度; 
		if( winform.progress.pos > len )
			winform.progress.pos = 0;
			
		table.push(缓冲表,下载数据 ) ; 
		win.delay(1)
	} 
	//whttp.endReuest();
	whttp.close();
	 
	var 完整数据 = string.join( 缓冲表 );
	
	var turl = inet.url.split(url) //拆分url
	tpath = io.splitpath(turl.path) //拆分路径
	var path = #tpath.file ? tpath.file : "index.html"; //生成本地保存路径
	string.save("/"+path,完整数据 ) //保存到应用程序根目录下
	process.explore_select("/"+path)
	
	winform.progress.hide = true;//隐藏进度条
	winform.button.disabled = false;//恢复被禁用的按钮
	
	
}

winform.show() 
win.loopMessage();
