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

import fsys;
import inet.http;
import process;
winform.button.oncommand = function(id,event){
	//禁用按钮,避免重复点击
	winform.button.disabled = true;
	
	//创建whttp对象
	var url = winform.editUrl.text;
	var whttp = inet.http();
	assert( whttp.beginRequest( url ) ) 
	var ok,code,contentLength = whttp.send(); 
	if(!ok) {
		winform.msgboxErr(code/*err*/,2);
		return;
	};
	
	//取得文件长度 
	if(contentLength){
		winform.labInfo.text = "文件大小: " + fsys.formatSize(contentLength);
	}
	else {
		winform.labInfo.text = "文件大小: 未知"
		contentLength = 1024 * 500 ;
	}
	
	//初始化进度条
	winform.progress.min = 0;
	winform.progress.max = 0xFFFF;
	winform.progress.pos = 0;
	winform.progress.hide = false;
	 
	var path = "/" + ..inet.url.getFileName(url);   
	var file = io.open( path,"w+b")
 
	var buffer = ..raw.buffer( 1024 );
	winform.progress.step = (contentLength / 0xFFFF) / 1024
	for( 长度 in whttp.eachReadBuffer(buffer) ){
		winform.progress.stepIt(); 
		file.writeBuffer(buffer,长度);
		win.delay(1)
	}   
	whttp.close();
	file.close();
	 
	process.explore_select(path)
	winform.progress.hide = true;//隐藏进度条
	winform.button.disabled = false;//恢复被禁用的按钮
}

winform.show() 
win.loopMessage();
