日期:2014-05-16  浏览次数:20403 次

javascript “异步”上传文件
var Uploader = (function(){
	/**
	 * @param options
	 * @param callback
	 * @returns
	 * @desc 创建iframe
	 */
	var iframe = function(options) {
		options = options || {
			id : 'iframe' + Math.random(),
			name : 'iframe',
			src : ''
		};
		var iframe;
		try{
			iframe = document.createElement('<iframe name=' + options.name + '>');
		}catch(e) {
			iframe = document.createElement('iframe');
			iframe.name = options.name;
		}
		options.id && (iframe.id = options.id);
		iframe.src = options.src;
		iframe.style.cssText = options.cssText;
		return iframe;
	};
	/**
	 * @param {file}
	 * @return {}
	 * @desc 上传文件
	 */
	function Uploader(file){
		var name,hidden;
		var uuid = Uploader.uuid++;
		this.state = 0;
		this.file = file;
		this.form = file.form;
		name = 'upload_file_'+ uuid;
		this.iframe = iframe({
			name:name,
			src:'blank.html',
			cssText:'display:none;'
		});
		document.body.appendChild(this.iframe);
		this.form.target = name;
	};
	Uploader.uuid = 0;
	Uploader.prototype = {
		upload:function(callback){
			//生成JSONP回调
			var ts,jsonp,uploader,action,jsonpCallback;
			ts = (new Date()).getTime();
			jsonp = 'jsonp' + ts;
			uploader = this;
			window[jsonp] = function(ret){
				callback(ret);
				uploader.state = 0;
			};
			action = this.form.action;
			jsonpCallback = 'parent.' + jsonp; 
			if(action.indexOf('callback') > -1){
				action = action.replace(/jsonp\d+/,jsonpCallback);
			}else{
				action += (action.indexOf('?') > -1 ? '&callback=' : '?callback=') + jsonpCallback;
			}
			this.form.action = action;
			this.state = 1;//开始上传
			this.form.submit();
			return jsonp;
		},
		readyState:function(){
			return this.state;
		},
		cancel:function(jsonp){
			typeof window[jsonp] && (window[jsonp] = function(){});
		}
	};
	return Uploader;
})();


这种上传文件的方法不会刷新页面,类似于Ajax。原理就是将要提交的表单target属性和页面中隐藏的iframe的name属性相等。实际就是iframe做提交
而iframe本身是不可见的,所以用户不会看到页面刷新的效果,请求成功或者失败服务器端都要返回一个script元素,该元素里面有一个
发送请求时候传递的回调函数callback,请求成功或者失败就会执行callback函数把服务器处理的结果作为回调函数传递到前端。

?

页面调用:

?

var file = document.getElementById('file'),uploader;
uploader = new Uploader(file);
uploader.upload(function(data){
        //成功或失败处理
});
?

?