HTML5文件上传功能开发 - Lidong's site 李东的博客

HTML5文件上传功能开发

好久没写博客了,最近在做中国好声音移动端项目的前端开发,之前完全没有接触过移动端项目的前端,所以还算是一个新人,要学的东西还有很多,特别是html5的一系列新的接口,确实方便了很多。

/*
**upload js
**author dongli
**date 2013.03.13
**1.获取上传文件大小,对上传文件的验证
**2.二次异步上传
**3.显示上传百分比,上传速度
*/
(function(doc){
	//缓存变量
	var uploadBtn = $('#file'),
		submitBtn = $('.submit'),
		error_type = $('#error'),
		error_problem = $('#error2'),
		abort = $('#abort'),
		warnsize = $('#warnsize'),
		progress_info = $('#progress_info'),
		progress = $('#progress'),
		progress_percent = $('#progress_percent'),
		b_transfered = $('#b_transfered'),
		speed = $('#speed'),
		remaining = $('#remaining'),
		upload_response = $('#upload_response');

	//定义变量
	var maxFileSize = 0,
		totalFileSize = 0,
		uploadedFileSize = 0,
		preloadedFileSize = 0,
		isSelected = 0;

	//controller控制层
	var controller = {
		//时间格式转换
		secondsToTime : function(secs){ 
		    var hr = Math.floor(secs / 3600);
		    var min = Math.floor((secs - (hr * 3600))/60);
		    var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

		    if (hr < 10) {hr = "0" + hr; } 
		    if (min < 10) {min = "0" + min;}
		    if (sec < 10) {sec = "0" + sec;}
		    if (hr) {hr = "00";}
		    return hr + ':' + min + ':' + sec;
		},
		//数据格式转换
		bytesToSize : function(bytes){
			var sizes = ['Bytes', 'KB', 'MB'];
			if (bytes == 0) return 'n/a';
			var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
			return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
		},
		//隐藏提示信息
		hideTips : function(){
			error_type.hide();
			error_problem.hide();
			abort.hide();
			warnsize.hide();
		},
		fileSelect : function(){
			// $('').appendTo('#upload_photo');
			controller.hideTips();
			var uFile = document.getElementById('file').files[0];
			totalFileSize = uFile.size;
			//对上传文件类型进行判断
			var uType = uFile.name.toString().split('.')[uFile.name.toString().split('.').length - 1];
			var rFilter = /^(wmv|rm|rmvb|flv|avi|mov)$/i;
			if (! rFilter.test(uType)) {
			    error_type.show();
			    return false;
			}
			//对上传文件大小进行判断
			// if(totalFileSize > maxFileSize){
			// 	warnsize.show();
			// 	return false;
			// }
			isSelected = 1;
		},
		uploadData : function(){
			if(isSelected){
				$.ajax({
					type : 'post',
					url : '/i/video/upload/query/',
					data : {
						'size' : totalFileSize,
						'title' : $('input[name="title"]').val(),
						'desc' : $('input[name="desc"]').val(),
						'priv' : $('#pp_upload').attr('checked') ? 0 : 3
					},
					success : function(r){
						console.log(r);
						controller.uploadFile(r);
					},
					error : function(){
						error_problem.show();
						return false;
					}
				})
			}
			else
				return false;
		},
		uploadFile : function(r){
			var oXHR = new XMLHttpRequest();
			var vFD = new FormData(document.getElementById('upload_photo'));
			vFD.append('type',4);
			vFD.append('id',r.id);
			vFD.append('size',totalFileSize);     
			vFD.append('outType',3);     
			oXHR.upload.addEventListener('progress', controller.uploadProgress, false);//文件上传百分比的事件
			oXHR.addEventListener('load', controller.uploadFinish, false);//文件上传完成事件
			oXHR.addEventListener('error', controller.uploadError, false);//文件上传的错误事件
			oXHR.addEventListener('abort', controller.uploadAbort, false);//文件上传的异常事件
			oXHR.open('POST', r.vto);
			oXHR.send(vFD);

			progress_info.show();
			timer = setInterval(controller.uploadSpeed, 500);
		},
		uploadProgress : function(e){
			if (e.lengthComputable) {
			    var iPercentComplete = Math.round(e.loaded * 100 / e.total);

			    uploadedFileSize = e.loaded;
			    progress_percent.html(iPercentComplete.toString() + '%');
			    progress.css('width',iPercentComplete.toString() + '%');
			    b_transfered.html(controller.bytesToSize(e.loaded));
			    //到100%时等待完成
			    if (iPercentComplete == 100) {
			        upload_response.html("处理中,请等待...").show();
			    }
			} else {
			    progress.html('unable to compute');
			}
		},
		uploadSpeed : function(){
			var uploadNow = uploadedFileSize;
			var uploadDiff = uploadNow - preloadedFileSize;
			//当前上传量和之前上传量比较没有变化即返回
			if (uploadDiff == 0)
			    return false;
			preloadedFileSize = uploadNow;
			//Interval设置为500毫秒,所以要*2按1秒计算时间和速度
			uploadDiff *= 2;
			//剩余量除1秒内上传量即为剩余秒数
			var secondsRemaining = (totalFileSize - preloadedFileSize) / uploadDiff;
			var iSpeed = uploadDiff.toString() + 'B/s';
			if (uploadDiff > 1024 * 1024) {
			    iSpeed = (Math.round(uploadDiff * 100/(1024*1024))/100).toString() + 'MB/s';
			} else if (uploadDiff > 1024) {
			    iSpeed =  (Math.round(uploadDiff * 100/1024)/100).toString() + 'KB/s';
			}
			speed.html(iSpeed);
			remaining.html('|' + controller.secondsToTime(secondsRemaining));
		},	
		uploadFinish : function(){
			// upload_response.html(e.target.responseText).show();
			console.log(event.target.responseText);
			progress_percent.html('100%');
			progress.css('width','100%');
			remaining.html('| 00:00:00');
			upload_response.html("上传成功!").show();
			clearInterval(timer);
		},
		uploadError : function(){
			error_problem.show();
			clearInterval(timer);
		},
		uploadAbort : function(){
			abort.show();
			clearInterval(timer);
		}
	};

	//事件绑定
	var bindEvents = function(){
		uploadBtn.change(function(){
			controller.fileSelect();
		});
		submitBtn.click(function(){
			controller.uploadData();
			return false;
		});
	};

	//事件调用
	bindEvents();
})(document)
相关的HTML的代码就不放了,很简单的,这里用了二次验证的异步上传文件,即第一次先用ajax把文件的信息post过去,服务器端判断没问题后返回文件上传的地址,之后在新建XMLHttpRequest对象来调用一些新的接口,并用form data来获取表单中的文件信息,这个在html4中基本是获取不到的。
这里用到了zepto.js框架,也就是移动端简化版的jQuery框架,主要也是用了一些方便的dom选择器和类型jQuery的ajax方法。

COMMENTS(4)

  • 1

    May 31 2016

    1111

  • aaa

    May 30 2013

    蛮好看的页面

  • sadasdas

    Apr 13 2014

    asdasdasdas

  • 大哥大

    May 22 2014

    强烈建议写html代码啊

LEAVE A COMMENT

Name:*

E-Mail:*

Website:

Message:*

Required fields are marked *

Post Comment