Nodejs+express+html5 实现拖拽上传_node.js(3)
该对象比较简单主要提供一个run以及setUrl方法,用于启动上传引擎,以及设置上传路径的功能。内部使用递归的方法把文件队列中的方法全部上传到服务端。使用uploadItemProgress通知外部上传的进度,使用uploadStatusChanged通知文件上传状态,以便更新UI.
uploaderApp.js中主要包括三个对象,一个是类似jquery的一个简单的jquery对象(App$)。主要用于绑定事件。一个是uploaderArea对象,是拖曳上传的窗口区域,另一个是入口对象uploaderMain对象。主要用于初始化对象,对外部提供一个init方法,来初始化整个对象。
了解关于App$以及uploaderArea对象的代码请下载 源代码 ,下面仅对uploaderMain对象做简单的说明。
(function (app) {
var _self;
function uploaderMain(id) {
this._id = id;
this._area = null;
this.uploaders = [];
this._URL = 'file/uploader';
}
uploaderMain.prototype = {
init: function () {
_self = this;
this._initArea();
this._initQueueEng();
},
_initQueueEng: function () {
uploaderQueue.Engine.setUrl(this._URL);
uploaderQueue.Engine.uploadStatusChanged = function (key, status) {
if (status === uploaderQueue.UploadStatus.Uploading) {
_self._area.hideItemCancel(key);
} else if (status === uploaderQueue.UploadStatus.Complete) {
_self._area.completeItem(key);
_self._area.showItemCancel(key);
}
}
uploaderQueue.Engine.uploadItemProgress = function (key, e) {
var progress = e.position / e.total;
_self._area.changeItemProgress(key, Math.round(progress * 100));
}
},
_initArea: function () {
this._area = new app.area(this._id);
this._area.init();
this._area.drop = function (e) {
var key = uploaderQueue.Queue.add({files: e.dataTransfer.files});
uploaderQueue.Engine.run();
return key;
}
this._area.cancelItem = function (key) {
uploaderQueue.Queue.remove(key);
}
}
};
app.main = uploaderMain;
})(window.uploaderApp);
在uploaderMain对象,相当于各个对象之间的中介,主要就是做对象的初始化功能、以及对象之间相互调用。使各个对象之间相互协作完成整个模块的功能。对外提供一个init方法来初始化整个程序,在html页面中只需如下代码:
<script type="text/javascript">
var main=new uploaderApp.main('container');
main.init();
</script>
以上代码就是创建一个入口对象,然后使用init方法来启动整个程序。
以上是对前端js的主要方法做的简单解释,如果想详细了解请下载源代码。下面简单看下后端js(nodejs)端实现的主要代码。
在express基础知识时,已经讲过在express已经对文件上传功能做了完整的封装,当路由到action时,文件已经完成上传只是文件上传到了一个临时目录,这个临时目录我们可以在app.js中配置的,配置方式如下:
app.use(express.bodyParser({
uploadDir:__dirname+'/public/temp'
}));






