断点上传中的javascript代码

//项目路径,例如:"/upload"
var contextPath ;
//显示速度百分比文件名的元素id
var ratePercent_id;
//是否已经上传完成
var isUploadComplete = 'false';
//查询上传速度百分比的时间间隔(值越小,频率越大)
var getRateInterval = 3000;
//页面经过多久之后去检验本地是否安装了客户端
var checkIsInstall_time_delay = 2000;
//文件上传成功之后,接收文件和参数信息的url
var _callbackURL;
//客户端获取授权的url
var getAuthorityURL;
//去查询用户选择的文件路径的定时器的时间间隔
var getFilePathInterval = 1000;
//将文件路径信息保存到服务器时的key
var key = Date.parse(new Date())+'-'+Math.random();
//获取上传服务器信息URL:
var _URL4UploadServerInfo;
//getAuthority的相应
var getAuthorityResponse;
var isShowRateLocal;
/**
 * 初始化服务器名称以及上传连接、速度百分比、文件名元素的id
 * @param {Object} path服务器名称
 * @param {Object} linkId上传连接
 * @param {Object} rateId速度
 * @param {Object} fileNameId文件名
 * @param {Object} percentId百分比
 */
function initContextPathAndIds(URL4UploadServerInfo,callbackURL,ratePercentId){
	if(! URL4UploadServerInfo){
		alert('请设置URL4UploadServerInfo的值');
	}
	if(! callbackURL){
		alert('请设置callbackURL的值');
	}
	_URL4UploadServerInfo = URL4UploadServerInfo;
	_callbackURL = callbackURL;
	if(ratePercentId){
		ratePercent_id = ratePercentId;
	}
	loadComplete();
}

/**
 * 遍历form中的所有元素,并生成对应的参数字符串
 */
function findAllFormElements(){
	var params = '';
	var element;
	//遍历input type=text元素(且有name属性)
	$("input:text[name]").each(function(){
		element = $(this);
		//如果没有value则返回
		if(! element.val()){
			return;
		}
		//说明不是第一个
		if(params){
			params += '&'+element.attr('name')+'='+element.val();
		//说明是第一个
		}else{
			params += element.attr('name')+'='+element.val();
		}
	});
	//遍历input type=password元素(且有name属性)
	$("input:password[name]").each(function(){
		element = $(this);
		//如果没有value则返回
		if(! element.val()){
			return;
		}
		//说明不是第一个
		if(params){
			params += '&'+element.attr('name')+'='+element.val();
		//说明是第一个
		}else{
			params += element.attr('name')+'='+element.val();
		}
	});
	//遍历input type=hidden元素(且有name属性)
	$("input[type='hidden'][name]").each(function(){
		element = $(this);
		//如果没有value则返回
		if(! element.val()){
			return;
		}
		//说明不是第一个
		if(params){
			params += '&'+element.attr('name')+'='+element.val();
		//说明是第一个
		}else{
			params += element.attr('name')+'='+element.val();
		}
	});
	//遍历input type=radio元素(且有name属性)
	$("input:radio[name]:checked").each(function(){
		element = $(this);
		//如果没有value则返回
		if(! element.val()){
			return;
		}
		//说明不是第一个
		if(params){
			params += '&'+element.attr('name')+'='+element.val();
		//说明是第一个
		}else{
			params += element.attr('name')+'='+element.val();
		}
	});
	//遍历input type=checkbox元素(且有name属性)
	$("input:checkbox[name]:checked").each(function(){
		element = $(this);
		//如果没有value则返回
		if(! element.val()){
			return;
		}
		//说明不是第一个
		if(params){
			params += '&'+element.attr('name')+'='+element.val();
		//说明是第一个
		}else{
			params += element.attr('name')+'='+element.val();
		}
	});
	//遍历select option元素(且有name属性)
	$("select[name] option:selected").each(function(){
		element = $(this);
		//如果没有value则返回
		if(! element.val()){
			return;
		}
		if(! element.parent("[name]")){
			return;
		}
		//说明不是第一个
		if(params){
			params += '&'+element.parent("[name]").attr('name')+'='+element.val();
		//说明是第一个
		}else{
			params += element.attr('name')+'='+element.val();
		}
	});
	return params;
}
var getFilePathTimeout;
/**
 * 初始化
 */
function loadComplete(){
	var file;
	if(! key){
		key = Date.parse(new Date())+'-'+Math.random();
	}
	$("input:file").each(function(i){
		file = $(this);
		file.bind('click',function(){
			try{
				//绑定事件,点击之后弹出文件选择框
				if(! file.attr("id")){
					alert('您尚未对file元素设定id');
					return false;
				}
				//先等待1000ms,让客户端有时间去向服务器发送请求,确保IsInstall的值被设置
				setTimeout("checkIsInstall()",checkIsInstall_time_delay);
				//调用客户端弹出文件选择框
				window.location = 'Luban://local_do=fileupload&choosefile=true&key='+key+"&contextPath="+ contextPath+"&id="+file.attr("id");
				if(getFilePathTimeout){
					clearTimeout(getFilePathTimeout);
				}
				//从点击file开始,过500ms开始去查询文件路径
				getFilePathTimeout = setTimeout("getFilePathFromServer()",500);
			}catch(e){}
			return false;
		});
	});
	//向_URL4UploadServerInfo地址发送get请求,并解析返回结果
	$.get(_URL4UploadServerInfo,function(data){
		if(data){
			//响应格式:uploadServerDomain=http://u.myluban.com&&URL4ApplyUploadAuth=http://www.google.com/applyUploadAuth4LubanAdmin
			contextPath = data.split('&&')[0].split('=')[1];
			getAuthorityURL = data.split('&&')[1].split('=')[1];
		}
	},"text");
}

/**
 * 获取授权信息
 */
function getAuthority(getAuthorityURL,href){
	$.get(getAuthorityURL,function(data){
		if(data){
			//响应格式:authSource=鲁班运维后台&&auth2User=刘夕波&&auth2UserType=2&&fileUpload2URL=http://u.myluban.com/fileupload&&
			//						authGenerateTime=1370422339758&&authExpiredTimeLen=30000&&sign=md5
			//由于客户端解析参数的时候会按照&拆分,所以把&&替换为##
			getAuthorityResponse = data.replace(/&&/g,'##');
			//将href保存到服务器
			sendHrefToServer(href);
		}
	},"text");
}
/**
 * 从服务器查询用户选择的文件的路径,显示在页面中
 */
function getFilePathFromServer(){
	var url = contextPath+'/lubanFileUpload/getFilePath';
	if(! key){
		key = Date.parse(new Date())+'-'+Math.random();
	}
	var param = {'key':key};
	//先将参数发送到服务器,发送成功之后再启动定时器检查本地是否安装了客户端
	$.post(url,param,function(data){
		if(data){
			//将data转为json格式
			data = eval("("+data+")");
			//点击了取消,没有选择文件
			if("cancel" == data.status){
				if(getFilePathTimeout){
					clearTimeout(getFilePathTimeout);
				}
				return;
			//点击了确认,选择了文件,要显示路径
			}else if("confirm" == data.status){
//				createAndShowFloatDiv(data.id,data.filePath);
				//alert(data.filePath);
				if(getFilePathTimeout){
					clearTimeout(getFilePathTimeout);
				}
				return;
			}
		}
		//说明还没有查询到结果,继续查询
		if(getFilePathTimeout){
			clearTimeout(getFilePathTimeout);
		}
		getFilePathTimeout = setTimeout("getFilePathFromServer()",getFilePathInterval);
	},"text");
}
/**
 * 创建并显示浮动层
 */
function createAndShowFloatDiv(id,filePath){
	var width = $("#"+id).width()*0.75;
	var height= $("#"+id).height();
	var top = $("#"+id).offset().top;
	var left =  $("#"+id).offset().left;
}
/**
 * 将上传参数保存到服务器
 */
function upload(){
	//格式为:uploadhelper://fileName=aaa.txt&fileName=bbb.txt&param=p1&param=p2
	var href = '';
	//循环所以的file,将其文件路径添加到链接后面
	if(isShowRateLocal){
		href += "isShowRateLocal=true";
	}
	if(_callbackURL){
		if(href){
			href += ("&callbackURL="+_callbackURL);
		}else{
			href += ("callbackURL="+_callbackURL);
		}
	}
	var param = findAllFormElements();
	if(param){
		if(href){
			href += ("&"+param);
		}else{
			href += (param);
		}
	}
	getAuthority(getAuthorityURL,href);
}

//定义一个定时器去显示下载速度和百分比
var getUploadRateTimeout ;

/**
 * 先判断本地是否安装了客户端,然后再查询上传速度百分比
 */
function confirmUpload(){
	upload();
	return false;
}
/**
 * 判断本地是否安装了客户端,然后再查询上传速度百分比
 */
function checkIsInstall(isUploadOrNot){
	var url = contextPath+'/lubanFileUpload/getIsInstall?key='+key;
	$.get(url,function(data){
		if(data != 'true'){
			var result = confirm('如果您还没有安装客户端程序,请点击确定下载客户端,下载之后双击程序进行注册表注册,如果您已经下载过客户端,' +
								'请选择取消,并重新双击该程序进行注册,注意:请不要将客户端存放在含有中文的目录下');
			if(result){
				window.location = contextPath+"/lubanFileUpload/downloadClient";
			}
		}
		//如果是点击的选择文件,则只需要调用客户端弹出文件选择框即可,不需要查询上传速度
		//如果是点击的上传文件,则需要查询上传速度
		if(isUploadOrNot){
			if(getUploadRateTimeout){
				clearTimeout(getUploadRateTimeout);
			}
			getUploadRateTimeout = setTimeout("getUploadRate()",0);
		}
	},"text");
}
/**
 *手动显示速度 
 */
 function showRate_manual(){
	if(getUploadRateTimeout){
		clearTimeout(getUploadRateTimeout);
	}
	getUploadRateTimeout = setTimeout("getUploadRate()",0);
 }
/**
 * 将上传参数保存到服务器
 */
function sendHrefToServer(href){
	if(! getAuthorityResponse){
		alert("尚未获取授权信息");
		//没有获取授权的Url地址,则无法获取授权
		return;
	}
	if(! contextPath){
		alert("尚未获取上传服务器信息");
		//没有获取contextPath地址
		return;
	}
	//添加上获取授权的url地址
	href += ("&getAuthorityResponse="+getAuthorityResponse);
	href = "Luban://"+encodeURI(encodeURI(href));
	var url = contextPath+'/lubanFileUpload/setHrefValue';
	if(! key){
		key = Date.parse(new Date())+'-'+Math.random();
	}
	var param = {'href':href,'key':key};
	//先将参数发送到服务器,发送成功之后再启动定时器检查本地是否安装了客户端
	$.post(url,param,function(){
		//先等待1000ms,让客户端有时间去向服务器发送请求,确保IsInstall的值被设置
		setTimeout("checkIsInstall('upload')",checkIsInstall_time_delay);
		window.location = "Luban://getArgumentsFromServer=true&local_do=fileupload&contextPath="+ contextPath +"&key="+key;
	},"text");
}
/**
 * 通过ajax查询上传速度和百分比
 */ 
function getUploadRate(){
	//首先检查显示速度信息的id是否存在,不存在的话就不需要查询速度信息
	if(! ratePercent_id){
		//如果ratePercent_id不存在,则认为不需要查询和显示速度百分比信息
		if(getUploadRateTimeout){
			//如果有查询速度百分比的定时器,则取消该定时器
			clearTimeout(getUploadRateTimeout);
		}
		return;
	}
	if(key){
		var url = contextPath+'/lubanFileUpload/getUploadRateAndPercent?time='+Date.parse(new Date())+"&key="+key;
	$.get(url,function(data){
		showRate(data);
	},"text");
	}
}
/**
 * 显示速度和百分比
 */
function showRate(data){
	if(data){
		var result = eval("("+data+")");
		$("#"+ratePercent_id).html('文件名:'+result.fileName+'<br/>'+'上传速度:'+result.rate+' kb/s'+'<br/>'+'上传百分比:'+result.percent+' %');
		if(result.isCompleted == 'true'){
			if(getUploadRateTimeout){
				clearTimeout(getUploadRateTimeout);
			}
			isUploadComplete = 'true';
			//执行上传完成的操作
			fileUploadComplete();
			//刷新
			window.location = window.location;
		}else if(result.isCompleted == 'interrupt'){
			if(getUploadRateTimeout){
				clearTimeout(getUploadRateTimeout);
			}
			isUploadComplete = 'break';
			//执行上传中断的操作
			fileUploadInterrupted();
			//刷新
			window.location = window.location;
		}else{
			if(getUploadRateTimeout){
				clearTimeout(getUploadRateTimeout);
			}
			getUploadRateTimeout = setTimeout("getUploadRate()",getRateInterval);
		}
	}else{
		if(getUploadRateTimeout){
				clearTimeout(getUploadRateTimeout);
			}
		getUploadRateTimeout = setTimeout("getUploadRate()",getRateInterval);
	}
}
function fileUploadComplete(){}
function fileUploadInterrupted(){}
/**
 * 获得页面的JSESSIONID
 * @return {TypeName} 
 */
function getSessionId(){
	var c_name = 'JSESSIONID';
	if(document.cookie.length>0){
	   c_start=document.cookie.indexOf(c_name + "=");
	   if(c_start!=-1){ 
	     c_start=c_start + c_name.length+1 ;
	     c_end=document.cookie.indexOf(";",c_start);
	     if(c_end==-1) c_end=document.cookie.length;
	     return unescape(document.cookie.substring(c_start,c_end));
	   }
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值