1. 서문
파일 업로드는 비교적 일반적인 기능입니다. 전통적인 업로드 방법이 더 번거 롭습니다. 먼저 업로드 버튼을 클릭 한 다음 파일의 경로를 찾은 다음 업로드해야합니다. 사용자 경험에 큰 문제가 발생합니다. HTML5는 업로드에 필요한 API를 드래그 앤 드롭을 지원하기 시작합니다. Nodejs는 또한 최근에 점점 인기를 얻고있는 기술입니다. 또한 Nodejs에 참여한 것은 이번이 처음입니다. NodeJS 개발에서 가장 일반적으로 사용되는 개발 프레임 워크 중 하나는 Expess이며, 이는 MVC 패턴과 유사한 프레임 워크입니다. HTML5 및 Nodejs Express와 결합하여 드래그 앤 드롭 업로드의 기능이 실현됩니다.
2. 기본 지식의 대중화
1. nodejs에 대한 기본 지식
간단히 말해서, Nodejs는 JS가 서버 측에서 실행할 수있는 개발 플랫폼입니다. Nodejs는 매우 빠르게 발전하고 있으며 Taobao와 같은 많은 국내 기업들도 사용하기 시작했습니다. 전통적인 웹 응용 프로그램 개발 플랫폼은 다중 스레딩에 의존하여 높은 일환 요청 응답을 달성합니다. 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 //www.vevb.com/article/48755.htm으로 시작하는 것에 대한 지식
2. Express의 기본 지식
Nodejs는 많은 타사 개발 라이브러리가있는 비교적 활발한 오픈 소스 커뮤니티이며, 그중에는 Express가 가장 광범위하고 가장 일반적으로 사용되는 프레임 워크 중 하나입니다. 또한 Nodejs가 권장하는 공식 프레임 워크입니다. 일반적인 HTTP 작업의 캡슐화 외에도 라우팅 제어, 템플릿 해상도 지원, 동적 시도, 사용자 답변 등을 구현하지만 전능 한 프레임 워크도 아닙니다. 대부분의 기능은 HTTP의 캡슐화이며, 단지 가벼운 프레임 워크 일뿐입니다. 많은 기능도 타사 라이브러리에 통합되어 구현해야합니다.
Exress는 매우 편리한 업로드 기능을 지원합니다. 파일 업로드 요청 후에는 Express가 파일을 수신하고 파일을 임시 디렉토리에 저장합니다. 그런 다음 라우팅 방법에서는 FIRTING 디렉토리에서 사용자 업로드를 저장하려는 폴더로 파일을 복사하면됩니다. 파일 업로드 부분에서 서버 측 구현은 Express 함수를 기반으로합니다.
3. HTML5 드래그 및 업로드 API
HTML5는 많은 새로운 기능을 제공하며 드래그 이벤트 및 파일 업로드는 새로운 기능 중 하나입니다. 공간이 제한되어 있기 때문에 드래그 업 업로드 된 코드 구현은 나중에 강조 표시됩니다. HTML5에서 제공 한 드래그 업로드 API를 하나씩 나열하지 않습니다. 관심이 있으시면 다음을 참조하십시오
3. 달성하려면 드래그 및 업로드
1. 코드 구현
먼저 프론트 엔드 JS의 파일 디렉토리를 살펴 보겠습니다.
안에:
Uploader.js는 주로 HTML5에서 지원하는 업로드 기능의 캡슐화를 구현합니다.
uploaderqueue.js는 주로 파일 큐를 업로드하는 관리를 구현하고 파일 업로드 객체를 서버에 파일 큐의 파일 업로드합니다.
UPLOADERAPP.JS 파일 업로드의 주요 입구는 주로 업로드 창을 구현하여 드래그 이벤트를 듣고 드래그 된 파일을 업로드 파일 큐에 푸시하고 파일 업로드 프로그램을 시작합니다.
다음은 핵심 코드 (필요)에 대한 간단한 설명입니다. 모든 코드는 여기에서 다운로드 할 수 있습니다 : FileUploader
먼저, html5에서 제공하는 파일 업로드를 위해 Uploader.js를 캡슐화하십시오.
함수 업 로더 (URL, 데이터, 파일) {this._files = 파일; this._data = 데이터; this._url = url; this._xhr = null; this.onloadStart = {}; this.onloadend = {}; this.onprogress = {}; this.onerror = {}; this.ontimeout = {}; this.callback = {}; // 요청이 완료된 후 콜백 _self = this; } UPLOADER.PROTOTYP = {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.onloadend = function (e) {evolfunction (_self.onloadend, e); }이. }; this._xhr.upload.onerror = function (e) {evolfunction (_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 (상태, 데이터); }}}}}, _createformData : function () {var formdata = new FormData (); this._addatatoformdata (formdata); this._addfiletoformdata (formdata); Return FormData; }, _ADDDATATOFORMDATA : function (formData) {if (this._data) {for (var it 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 ( '파일 [' + i + ']', this._files [i]); }}}}}; CodeVar uploaderFactory = {send : function (url, data, files, 콜백) {var insuploader = new Uploader (url, data, files); insuploader.callback = function (status, resdata) {if (callback === 'function') {Callback (status, resdata); }} insuploader.send (); 리턴 인스 수스 로더; }};업 로더 객체는 주로 HTML5에서 제공하는 기본 API를 단순히 캡슐화합니다. UploadErfactory는 간단한 인터페이스를 제공합니다.이 인터페이스는 jQuery의 AJAX 메소드 인 파일 업로드 호출과 같이 수행 할 수 있습니다. HTML5에 제공된 파일 업로드에 대한 지원은 원래 XMLHTTPREQUEST를 기반으로 일부 속성 및 메소드를 확장하고 FormData 객체를 제공하여 파일 업로드 작업을 지원하는 것입니다.
파일 업로드 큐 (uploaderqueue.js)도 비교적 중요한 객체입니다. 여기에는 두 개의 객체, 하나는 큐, 파일 큐 개체가 포함되어 있으며, 주로 파일 큐의 추가, 삭제, 수정 및 쿼리 관리를 담당합니다. 다른 객체는 파일 업로드 엔진 인 uploadEngine입니다. 이 기능은 주로 파일 큐에서 파일 객체를 제거하고 파일 업로드를 위해 업로더 객체를 호출 한 다음 파일 큐에서 파일 상태를 업데이트하는 데 책임이 있습니다. 대기열과 업로드 엔진은 싱글 톤 객체입니다.
먼저 파일 큐 객체를 살펴 보겠습니다.
(function (upladerqueue) {var status = {ready : 0, 업로드 : 1, 완료 : 2} var _self = null; var instance = null; function queue () {this._datas = []; this._cursize = 0; // current longey = this;} queue.prototyp = {var key = gettime () {). {key : 데이터 : 상태. var index 이. }} 반환 -1; }, getDatabyIndex : function (index) {if (index <0) {return null; } retract._datas [index]; }, _getIndexBykey : 함수 (key) {for (var i = 0; i <this._datas.length; i ++) {if (this._datas [i] .key == key) {return i; }} 반환 -1; }}; 함수 getInstace () {if (instance === null) {instance = new queue (); 반환 인스턴스; } else {return instance; }} upladerqueue.queue = getinstance (); upladerqueue.uploadstatus = status;}) (window.uploaderqueue);업로드 파일 큐는 배열을 사용하여 각 파일 객체의 정보를 관리합니다. 각 파일 객체에는 키, 데이터 및 상태의 세 가지 속성이 있습니다. 이 개체는 주로 파일 개체를 추가, 삭제, 업데이트 및 검색하는 기능을 담당합니다.
업로드 파일 큐의 또 다른 더 중요한 객체는 엔진 개체 업로드 (uploadEngine.js)입니다.
(function (upladerqueue) {var instance = null; var _self; function uploadEngine () {this._url = null; this._curuploadingkey = -1; // flags this.uploadstatusChanged = {}; this.uploaditemProgress = {}; {this._url = url} : function (this._curuploadingkey === && this._URL), {index uploaderfactory.send (this._url, null, files, function, data) {_self._completeduploaditem.call (_self, status, data); _self.uploaditemProgress (_self._curuploadingkey, e); }}, _readyUploadItem : function (index) {this._curuploadingkey = upladerqueue.queue.getDatabyIndex (index) .key; if (this.uploadstatusChanged === 'function') {this.uploadstatusChanged (this._curuploadingkey, upladerqueue.uploadstatus.uploading); } upladerqueue.queue.setitemstatus (this._curuploadingkey, upladerqueue.uploadstatus.uploading); }, _completeDuploadItem : 함수 (상태, 데이터) {if (type this.uploadstatusChanged === 'function') {this.uploadstatusChanged (this._curuploadingkey, upladerqueue.uploadstatus.complete); } upladerqueue.queue.setitemstatus (this._curuploadingkey, upladerqueue.uploadstatus.complete); this._startupload (); }}; 함수 getInstace () {if (instance === null) {instance = new UploadEngine (); } return 인스턴스; } upladerqueue.engine = getInstace ();}) (window.uploaderqueue);이 객체는 비교적 간단하며 주로 실행 및 SetUll 메소드를 제공하며 업로드 엔진을 시작하고 업로드 경로를 설정하는 데 사용됩니다. 재귀 메소드는 내부적으로 사용하여 파일 큐의 모든 메소드를 서버에 업로드합니다. UPLOADITEMPROGRESS를 사용하여 외부 업로드의 진행 상황을 알리고 UPLOADSTATUSCHANGED를 사용하여 파일 업로드 상태를 알리려면 UI를 업데이트하십시오.
UPLOADERAPP.JS에는 주로 세 개의 객체가 포함되어 있으며, 하나는 jQuery와 유사한 간단한 jQuery 객체 (app $)입니다. 주로 바인딩 이벤트에 사용됩니다. 하나는 업로드 레레아 객체이며, 드래그 및 업로드 된 창 영역이고 다른 하나는 입구 개체 인 UploaderMain 객체입니다. 주로 객체를 초기화하는 데 사용되며 전체 객체를 초기화하기 위해 외부에 초기 메소드를 제공합니다.
App $ 및 UploaderArea 개체에 대한 코드에 대해 알아 보려면 소스 코드를 다운로드하십시오. 다음은 업로드 메인 오브젝트에 대한 간단한 설명 일뿐입니다.
(function (app) {var _self; function uploadermain (id) {this._id = id; this._area = null; this.uploaders = []; this._url = '파일/업 로더';} uploadermain.prototype = {init : function () {_self = this; this._initarea (); this._initqueeng (); _initqueueng : function () {uploaderqueue.engine.seturl (this._url); uploaderqueue.uploadstatus.complete) {_self._area.completeitem (key); uploaderqueue.engine.uploaditemprogress (key, e) {var e * 10)}, _initarea : this._area (this._area.init); this._area.cancelitem = function (key) {uploaderqueue.queue.remove (key); }}}; app.main = 업로드 어메인; }) (window.uploaderApp);업로드 메인 오브젝트는 각 객체 사이의 중개자와 동일하며, 주로 객체의 초기화 함수를 만들고 객체 사이에서 서로 호출합니다. 각 객체가 서로 협력하여 전체 모듈의 기능을 완료하십시오. 전체 프로그램을 초기화하기위한 Init 메소드를 제공하십시오. HTML 페이지에는 다음 코드가 필요합니다.
<script type = "text/javaScript"> var main = new UploaderApp.Main ( '컨테이너'); main.init (); </script>
위의 코드는 항목 객체를 작성한 다음 Init 메소드를 사용하여 전체 프로그램을 시작하는 것입니다.
위는 프론트 엔드 JS의 주요 방법에 대한 간단한 설명입니다. 더 알고 싶다면 소스 코드를 다운로드하십시오. 백엔드 JS (Nodejs) 측면 구현의 기본 코드를 살펴 보겠습니다.
Express의 기본 사항에서, 우리는 이미 파일 업로드 기능이 Express에서 완전히 캡슐화되었다고 말했습니다. 작업으로 라우팅 할 때 파일이 임시 디렉토리에 업로드 된 경우에만 파일이 업로드되었습니다. 이 임시 디렉토리를 app.js에서 구성 할 수 있습니다. 구성 방법은 다음과 같습니다.
app.use (express.bodyparser ({uploaddir : __ dirname+'/public/temp'}));이러한 방식으로 파일이 업로드 된 후 파일은 /public /temp 디렉토리에 저장되며 파일 이름은 특정 알고리즘을 통해 Express에 의해 무작위로 얻어집니다. 우리가 쓴 조치에서, 우리는 임시 디렉토리의 파일을 서버에 저장된 디렉토리로 만 이동 한 다음 임시 디렉토리에서 파일을 삭제하면됩니다. 특정 코드는 다음과 같습니다.
함수 업 로더 (req, res) {if (req.files! = 'undifened') {console.dir (req.files); utils.mkdir (). 그런 다음 (함수 (path) {uploadfile (req, res, path, 0);}); }} 함수 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); 이름 바꾸기 (temppath, path + name) .then (function () {var unlink = promise.denodeify (fs.unlink); unlink (temppath);}). 다음 (function () {if (index == req.files.file.length -1) {var res = {코드 : 1, des : 'uploaded'}; uploadfile (req, res, path, index + 1); }}2. 효과를 실현하십시오
4. 코드를 받으십시오
코드 다운로드 주소 : //www.vevb.com/jiaoben/202117.html