>  기사  >  웹 프론트엔드  >  Nodejs express html5는 드래그 앤 드롭 upload_node.js를 구현합니다.

Nodejs express html5는 드래그 앤 드롭 upload_node.js를 구현합니다.

WBOY
WBOY원래의
2016-05-16 16:40:031370검색

1. 서문

파일 업로드는 비교적 일반적인 기능입니다. 기존 선택 방법은 먼저 업로드 버튼을 클릭한 다음 파일 경로를 찾아 업로드해야 합니다. 이는 사용자 경험에 큰 문제를 가져옵니다. HTML5는 드래그 앤 드롭 업로드에 필요한 API를 지원하기 시작합니다. Nodejs는 최근 점점 더 인기를 얻고 있는 기술이기도 합니다. 이것은 nodejs 개발에서 가장 일반적으로 사용되는 개발 프레임워크 중 하나이며 mvc 모델과 유사한 프레임워크입니다. HTML5 및 nodejs express와 결합하여 드래그 앤 드롭 업로드 기능이 구현됩니다.

2. 기초지식의 대중화

1. NodeJ에 대한 기본 지식

Nodejs는 단순히 서버에서 js를 실행할 수 있게 해주는 개발 플랫폼입니다. Nodejs는 매우 빠르게 발전하고 있으며, 타오바오 등 많은 국내 기업들이 이를 사용하기 시작했습니다. 기존 웹 애플리케이션 개발 플랫폼은 동시성이 높은 요청에 응답하기 위해 멀티스레딩을 사용합니다. Nodejs는 단일 스레드, 비동기식 IO 및 이벤트 중심 설계 모델을 채택하여 nodejs의 성능을 크게 향상시킵니다. 이는 nodejs의 가장 큰 특징이기도 합니다. nodejs에서는 모든 IO 작업이 콜백을 통해 수행됩니다. nodejs는 IO 작업을 수행할 때 IO 요청을 이벤트 큐에 푸시하고 프로그램이 이를 처리할 때까지 기다립니다. 처리된 후 호출합니다. 콜백 함수가 결과를 반환합니다.

예를 들어 데이터베이스를 쿼리할 때 작업은 다음과 같습니다.

mysql.query("SELECT * FROM myTable",function(res){
       callback(res);  
});

위 코드에서 nodejs는 위 명령문을 실행할 때 데이터베이스가 결과를 반환할 때까지 기다리지 않고 다음 명령문을 계속 실행합니다. 데이터베이스가 데이터를 얻은 후에는 이벤트 루프 큐로 전송되며 스레드가 이벤트 루프 큐에 들어갈 때까지 콜백이 실행되지 않습니다.

nodejs에 대한 더 많은 지식에 대해 이틀 동안 읽었지만 아는 바가 많지 않습니다. 더 자세히 알아보려면 인터넷에서 검색해 보세요.

nodejs 지식 소개 http://www.nodebeginner.org/index-zh-cn.html http://www.jb51.net/article/48755.htm

2. 표현의 기본지식

Nodejs는 상대적으로 활동적인 오픈 소스 커뮤니티입니다. 여기에는 수많은 타사 개발 라이브러리가 있으며, 그중 Express는 가장 광범위하고 일반적으로 사용되는 프레임워크 중 하나입니다. 또한 공식적으로 권장되는 nodejs 프레임워크이기도 합니다. 일반적인 http 작업을 캡슐화하는 것 외에도 라우팅 제어, 템플릿 구문 분석 지원, 동적 보기, 사용자 응답 등도 구현합니다. 하지만 이는 보편적인 프레임워크가 아니며 대부분의 기능은 http 캡슐화일 뿐입니다. 또한 많은 기능을 구현하려면 타사 라이브러리와 통합해야 합니다.

Express는 매우 편리한 업로드 기능 지원을 제공합니다. Express는 파일을 수신하여 임시 디렉터리에 저장합니다. 그런 다음 라우팅 방법에서는 임시 디렉터리에서 파일을 복사하기만 하면 됩니다. 사용자 업로드를 저장하려는 폴더로 이동합니다. 파일 업로드 부분에서 서버 측 구현은 express 기능을 기반으로 합니다.

3.html5 드래그 업로드 API

HTML5는 많은 새로운 기능을 제공하며 드래그 앤 드롭 이벤트와 파일 업로드는 새로운 기능 중 하나입니다. 제한된 공간으로 인해 나중에 드래그 앤 드롭 업로드의 코드 구현에 중점을 둘 것입니다. HTML5에서 제공하는 드래그 앤 드롭 업로드 API를 하나씩 나열하지는 않겠습니다. 관심 있으신 분은 http://w3school.com.cn/html5/html5_ref_eventattributes.asp#Mouse_Events http://www.jb51.net/html5/85977.html

3. 드래그 앤 드롭 업로드 구현

1. 코드 구현

먼저 프론트엔드 js의 파일 디렉터리를 살펴보겠습니다.

그 중:

uploader.js는 주로 html5에서 지원하는 업로드 기능의 캡슐화를 구현합니다.

uploaderQueue.js는 주로 파일 업로드 대기열 관리와 파일 업로드 객체 관리를 구현하고, 파일 대기열에 있는 파일을 서버에 업로드합니다.

uploaderApp.js는 파일 업로드를 위한 주요 진입점으로, 주로 업로드 창에서 드래그 이벤트 모니터링을 구현하고 드래그된 파일을 업로드 파일 대기열에 푸시하며 파일 업로드 프로그램을 시작합니다.

다음은 핵심 코드에 대한 간략한 설명입니다(필수). 모든 코드는 여기에서 다운로드할 수 있습니다: FileUploader

먼저 html5 uploader.js에서 제공하는 파일 업로드를 간단히 캡슐화합니다

function uploader(url, data, files) {
  this._files = files;
  this._data = data;
  this._url = url;

  this._xhr = null;

  this.onloadstart = {};
  this.onload = {};
  this.onloadend = {};
  this.onprogress = {};
  this.onerror = {};
  this.ontimeout = {};
  this.callback = {};//请求完成后回调
  _self = this;
 }

 uploader.prototype = {
  init: function () {
   if (!isValid()) {
    throw e;
   }
   this._xhr = new XMLHttpRequest();
   this._bindEvents();
  },
  send: function () {
   if (this._xhr == null) {
    this.init();
   }
   var formData = this._createFormData();
   this._xhr.open('post', this._url, true);
   this._xhr.send(formData);
  },
  _bindEvents: function () {
   _self = this;
   this._xhr.upload.loadstart = function (e) {
    evalFunction(_self.onloadstart, e);
   }
   this._xhr.upload.onload = function (e) {
    evalFunction(_self.onload, e);
   };
   this._xhr.upload.onloadend = function (e) {
    evalFunction(_self.onloadend, e);
   }
   this._xhr.upload.onprogress = function (e) {
    evalFunction(_self.onprogress, e)
   };
   this._xhr.upload.onerror = function (e) {
    evalFunction(_self.onerror, e);
   };
   this._xhr.upload.ontimeout = function (e) {
    evalFunction(_self.ontimeout, e);
   }

   this._xhr.onreadystatechange = function () {
    if (_self._xhr.readyState == 4) {
     if (typeof _self.callback === 'function') {
      var status = _self._xhr.status;
      var data = _self._xhr.responseText;
      _self.callback(status, data);
     }
    }
   }
  },
  _createFormData: function () {
   var formData = new FormData();
   this._addDataToFormData(formData);
   this._addFileToFormData(formData);
   return formData;
  },
  _addDataToFormData: function (formData) {
   if (this._data) {
    for (var item in this._data) {
     formData.append(item, this._data[item]);
    }
   }
  },
  _addFileToFormData: function (formData) {
   if (this._files) {
    for (var i = 0; i < this._files.length; i++) {
     var file = this._files[i];
     formData.append('file[' + i + ']', this._files[i]);
    }
   }
  }
 };
View Code
var uploaderFactory = {
  send: function (url, data, files, callback) {
   var insUploader = new uploader(url, data, files);
   insUploader.callback = function (status, resData) {
    if (typeof callback === 'function') {
     callback(status, resData);
    }
   }
   insUploader.send();
   return insUploader;
  }
 };

uploader对象主要是对html5提供的原生api进行简单的封装。uploaderFactory提供一个简单的接口,使用它可以像jquery的ajax方法一样完成,文件上传调用。html5中提供的文件上传的支持,是在原来XMLHttpRequest基础之上扩展一些属性和方法,提供了FormData对象,来支持文件上传操作。

文件上传队列(uploaderQueue.js)也是一个比较重要的对象,它包括两个对象一个是Queue,文件队列对象,主要负责管理文件队列的增删改查询等操作,另一个对象是UploadEngine,文件上传引擎,它的功能主要是负责从文件队列中取出文件对象,调用uploader对象上传文件,然后更新文件队列中的文件状态。Queue以及UploadEngine都是单例对象。

首先来看下文件队列对象:

(function (upladerQueue) {

 var Status = {
  Ready: 0,
  Uploading: 1,
  Complete: 2
 }

 var _self = null;

 var instance = null;

 function Queue() {
  this._datas = [];
  this._curSize = 0;//当前长度


  _self = this;
 }

 Queue.prototype = {
  add: function (data) {
   var key = new Date().getTime();
   this._datas.push({key: key, data: data, status: Status.Ready});
   this._curSize = this._datas.length;
   return key;
  },
  remove: function (key) {
   var index = this._getIndexByKey(key);
   this._datas.splice(index, 1);
   this._curSize = this._datas.length;
  },
  get: function (key) {
   var index = this._getIndexByKey(key);
   return index != -1 &#63; this._datas[index].data : null;
  },
  clear: function () {
   this._datas = [];
   this._curSize = this._datas.length;
  },
  size: function () {
   return this._curSize;
  },
  setItemStatus: function (key, status) {
   var index = this._getIndexByKey(key);
   if (index != -1) {
    this._datas[index].status = status;
   }
  },
  nextReadyingIndex: function () {
   for (var i = 0; i < this._datas.length; i++) {
    if (this._datas[i].status == Status.Ready) {
     return i;
    }
   }
   return -1;
  },
  getDataByIndex: function (index) {
   if (index < 0) {
    return null;
   }
   return this._datas[index];
  },
  _getIndexByKey: function (key) {
   for (var i = 0; i < this._datas.length; i++) {
    if (this._datas[i].key == key) {
     return i;
    }
   }
   return -1;
  }
 };

 function getInstace() {
  if (instance === null) {
   instance = new Queue();
   return instance;
  } else {
   return instance;
  }
 }


 upladerQueue.Queue = getInstace();
 upladerQueue.UploadStatus = Status;
})(window.uploaderQueue);

上传文件队列使用一个数组管理每个文件对象信息,每个文件对象有key,data,status三个属性,该对象主要负责文件对象的增加、删除、更新、查找的功能。

上传文件队列中另一个比较重要的对象是上传引擎对象(uploadEngine.js)

(function (upladerQueue) {

 var instance = null;
 var _self;

 function uploadEngine() {
  this._url = null;
  this._curUploadingKey = -1;//标志
  this.uploadStatusChanged = {};
  this.uploadItemProgress={};
  _self = this;
 }

 uploadEngine.prototype = {
  setUrl: function (url) {
   this._url = url;
  },
  run: function () {
   if (this._curUploadingKey === -1 && this._url) {
    this._startUpload();
   }
  },
  _startUpload: function () {
   _self = this;
   var index = upladerQueue.Queue.nextReadyingIndex();
   if (index != -1) {
    this._uploadItem(index);
   } else {
    this._curUploadingKey = -1;
    return null;
   }
  },
  _uploadItem: function (index) {
   var data = upladerQueue.Queue.getDataByIndex(index).data;
   _self = this;
   this._readyUploadItem(index);
   var upload = uploaderFactory.send(this._url, null, data.files, function (status, data) {
    _self._completedUploadItem.call(_self, status, data);
   });

   this._uploadItemProgress(upload);
  },
  _uploadItemProgress: function (upload) {
   upload.onprogress = function (e) {
     _self.uploadItemProgress(_self._curUploadingKey,e);
   }
  },
  _readyUploadItem: function (index) {
   this._curUploadingKey = upladerQueue.Queue.getDataByIndex(index).key;
   if (typeof this.uploadStatusChanged === 'function') {
    this.uploadStatusChanged(this._curUploadingKey, upladerQueue.UploadStatus.Uploading);
   }
   upladerQueue.Queue.setItemStatus(this._curUploadingKey, upladerQueue.UploadStatus.Uploading);
  },
  _completedUploadItem: function (status, data) {
   if (typeof this.uploadStatusChanged === 'function') {
    this.uploadStatusChanged(this._curUploadingKey, upladerQueue.UploadStatus.Complete);
   }
   upladerQueue.Queue.setItemStatus(this._curUploadingKey, upladerQueue.UploadStatus.Complete);
   this._startUpload();
  }
 };

 function getInstace() {
  if (instance === null) {
   instance = new uploadEngine();
  }
  return instance;
 }

 upladerQueue.Engine = getInstace();
})(window.uploaderQueue);

该对象比较简单主要提供一个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'
}));

这样在文件上传后文件就存放在/public/temp目录下,文件名也是express通过一定的算法随机获取的。在我们写的action中只需要把存在临时目录中的文件移动到服务端存放文件的目录下,然后删除临时目录下的文件即可。具体代码如下:

function uploader(req, res) {
 if (req.files != 'undifined') {
  console.dir(req.files);
  utils.mkDir().then(function (path) {
   uploadFile(req, res, path, 0);
  });

 }
}

function uploadFile(req, res, path, index) {
 var tempPath = req.files.file[index].path;
 var name = req.files.file[index].name;
 if (tempPath) {
  var rename = promise.denodeify(fs.rename);
  rename(tempPath, path + name).then(function () {
   var unlink = promise.denodeify(fs.unlink);
   unlink(tempPath);
  }).then(function () {
    if (index == req.files.file.length - 1) {
     var res = {
      code: 1,
      des: '上传成功'
     };
     res.send(res);
    } else {
     uploadFile(req, res, path, index + 1);
    }
   });
 }
}

2、实现效果

四、获取代码

 代码下载地址:http://www.jb51.net/jiaoben/202117.html

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.