fileuploader.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. /*
  2. Multiple file upload component with progress-bar, drag-and-drop.
  3. http://github.com/valums/file-uploader
  4. Copyright (C) 2011 by Andris Valums
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. */
  21. //
  22. // Helper functions
  23. //
  24. var qq = qq || {};
  25. /**
  26. * Adds all missing properties from second obj to first obj
  27. */
  28. qq.extend = function(first, second){
  29. for (var prop in second){
  30. first[prop] = second[prop];
  31. }
  32. };
  33. /**
  34. * Searches for a given element in the array, returns -1 if it is not present.
  35. * @param {Number} [from] The index at which to begin the search
  36. */
  37. qq.indexOf = function(arr, elt, from){
  38. if (arr.indexOf) return arr.indexOf(elt, from);
  39. from = from || 0;
  40. var len = arr.length;
  41. if (from < 0) from += len;
  42. for (; from < len; from++){
  43. if (from in arr && arr[from] === elt){
  44. return from;
  45. }
  46. }
  47. return -1;
  48. };
  49. qq.getUniqueId = (function(){
  50. var id = 0;
  51. return function(){ return id++; };
  52. })();
  53. //
  54. // Events
  55. qq.attach = function(element, type, fn){
  56. if (element.addEventListener){
  57. element.addEventListener(type, fn, false);
  58. } else if (element.attachEvent){
  59. element.attachEvent('on' + type, fn);
  60. }
  61. };
  62. qq.detach = function(element, type, fn){
  63. if (element.removeEventListener){
  64. element.removeEventListener(type, fn, false);
  65. } else if (element.attachEvent){
  66. element.detachEvent('on' + type, fn);
  67. }
  68. };
  69. qq.preventDefault = function(e){
  70. if (e.preventDefault){
  71. e.preventDefault();
  72. } else{
  73. e.returnValue = false;
  74. }
  75. };
  76. //
  77. // Node manipulations
  78. /**
  79. * Insert node a before node b.
  80. */
  81. qq.insertBefore = function(a, b){
  82. b.parentNode.insertBefore(a, b);
  83. };
  84. qq.remove = function(element){
  85. element.parentNode.removeChild(element);
  86. };
  87. qq.contains = function(parent, descendant){
  88. // compareposition returns false in this case
  89. if (parent == descendant) return true;
  90. if (parent.contains){
  91. return parent.contains(descendant);
  92. } else {
  93. return !!(descendant.compareDocumentPosition(parent) & 8);
  94. }
  95. };
  96. /**
  97. * Creates and returns element from html string
  98. * Uses innerHTML to create an element
  99. */
  100. qq.toElement = (function(){
  101. var div = document.createElement('div');
  102. return function(html){
  103. div.innerHTML = html;
  104. var element = div.firstChild;
  105. div.removeChild(element);
  106. return element;
  107. };
  108. })();
  109. //
  110. // Node properties and attributes
  111. /**
  112. * Sets styles for an element.
  113. * Fixes opacity in IE6-8.
  114. */
  115. qq.css = function(element, styles){
  116. if (styles.opacity != null){
  117. if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
  118. styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
  119. }
  120. }
  121. qq.extend(element.style, styles);
  122. };
  123. qq.hasClass = function(element, name){
  124. var re = new RegExp('(^| )' + name + '( |$)');
  125. return re.test(element.className);
  126. };
  127. qq.addClass = function(element, name){
  128. if (!qq.hasClass(element, name)){
  129. element.className += ' ' + name;
  130. }
  131. };
  132. qq.removeClass = function(element, name){
  133. var re = new RegExp('(^| )' + name + '( |$)');
  134. element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
  135. };
  136. qq.setText = function(element, text){
  137. element.innerText = text;
  138. element.textContent = text;
  139. };
  140. //
  141. // Selecting elements
  142. qq.children = function(element){
  143. var children = [],
  144. child = element.firstChild;
  145. while (child){
  146. if (child.nodeType == 1){
  147. children.push(child);
  148. }
  149. child = child.nextSibling;
  150. }
  151. return children;
  152. };
  153. qq.getByClass = function(element, className){
  154. if (element.querySelectorAll){
  155. return element.querySelectorAll('.' + className);
  156. }
  157. var result = [];
  158. var candidates = element.getElementsByTagName("*");
  159. var len = candidates.length;
  160. for (var i = 0; i < len; i++){
  161. if (qq.hasClass(candidates[i], className)){
  162. result.push(candidates[i]);
  163. }
  164. }
  165. return result;
  166. };
  167. /**
  168. * obj2url() takes a json-object as argument and generates
  169. * a querystring. pretty much like jQuery.param()
  170. *
  171. * how to use:
  172. *
  173. * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
  174. *
  175. * will result in:
  176. *
  177. * `http://any.url/upload?otherParam=value&a=b&c=d`
  178. *
  179. * @param Object JSON-Object
  180. * @param String current querystring-part
  181. * @return String encoded querystring
  182. */
  183. qq.obj2url = function(obj, temp, prefixDone){
  184. var uristrings = [],
  185. prefix = '&',
  186. add = function(nextObj, i){
  187. var nextTemp = temp
  188. ? (/\[\]$/.test(temp)) // prevent double-encoding
  189. ? temp
  190. : temp+'['+i+']'
  191. : i;
  192. if ((nextTemp != 'undefined') && (i != 'undefined')) {
  193. uristrings.push(
  194. (typeof nextObj === 'object')
  195. ? qq.obj2url(nextObj, nextTemp, true)
  196. : (Object.prototype.toString.call(nextObj) === '[object Function]')
  197. ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
  198. : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
  199. );
  200. }
  201. };
  202. if (!prefixDone && temp) {
  203. prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
  204. uristrings.push(temp);
  205. uristrings.push(qq.obj2url(obj));
  206. } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
  207. // we wont use a for-in-loop on an array (performance)
  208. for (var i = 0, len = obj.length; i < len; ++i){
  209. add(obj[i], i);
  210. }
  211. } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
  212. // for anything else but a scalar, we will use for-in-loop
  213. for (var i in obj){
  214. add(obj[i], i);
  215. }
  216. } else {
  217. uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
  218. }
  219. return uristrings.join(prefix)
  220. .replace(/^&/, '')
  221. .replace(/%20/g, '+');
  222. };
  223. //
  224. //
  225. // Uploader Classes
  226. //
  227. //
  228. var qq = qq || {};
  229. /**
  230. * Creates upload button, validates upload, but doesn't create file list or dd.
  231. */
  232. qq.FileUploaderBasic = function(o){
  233. this._options = {
  234. // set to true to see the server response
  235. debug: false,
  236. action: '/server/upload',
  237. dest: '/',
  238. fileFieldLabel: 'hdfs_file',
  239. params: {},
  240. button: null,
  241. multiple: true,
  242. maxConnections: 3,
  243. // validation
  244. allowedExtensions: [],
  245. sizeLimit: 0,
  246. minSizeLimit: 0,
  247. // events
  248. // return false to cancel submit
  249. onSubmit: function(id, fileName){},
  250. onProgress: function(id, fileName, loaded, total){},
  251. onComplete: function(id, fileName, responseJSON){},
  252. onCancel: function(id, fileName){},
  253. // messages
  254. messages: {
  255. typeError: "{file} has invalid extension. Only {extensions} are allowed.",
  256. sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
  257. minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
  258. emptyError: "{file} is empty, please select files again without it.",
  259. onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
  260. },
  261. showMessage: function(message){
  262. alert(message);
  263. }
  264. };
  265. qq.extend(this._options, o);
  266. // number of files being uploaded
  267. this._filesInProgress = 0;
  268. this._handler = this._createUploadHandler();
  269. if (this._options.button){
  270. this._button = this._createUploadButton(this._options.button);
  271. }
  272. this._preventLeaveInProgress();
  273. };
  274. qq.FileUploaderBasic.prototype = {
  275. setParams: function(params){
  276. this._options.params = params;
  277. },
  278. getInProgress: function(){
  279. return this._filesInProgress;
  280. },
  281. _createUploadButton: function(element){
  282. var self = this;
  283. return new qq.UploadButton({
  284. element: element,
  285. multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
  286. onChange: function(input){
  287. self._onInputChange(input);
  288. }
  289. });
  290. },
  291. _createUploadHandler: function(){
  292. var self = this,
  293. handlerClass;
  294. if(qq.UploadHandlerXhr.isSupported()){
  295. handlerClass = 'UploadHandlerXhr';
  296. } else {
  297. handlerClass = 'UploadHandlerForm';
  298. }
  299. var handler = new qq[handlerClass]({
  300. debug: this._options.debug,
  301. action: this._options.action,
  302. dest: '/',
  303. fileFieldLabel:'hdfs_file',
  304. maxConnections: this._options.maxConnections,
  305. onProgress: function(id, fileName, loaded, total){
  306. self._onProgress(id, fileName, loaded, total);
  307. self._options.onProgress(id, fileName, loaded, total);
  308. },
  309. onComplete: function(id, fileName, result){
  310. self._onComplete(id, fileName, result);
  311. self._options.onComplete(id, fileName, result);
  312. },
  313. onCancel: function(id, fileName){
  314. self._onCancel(id, fileName);
  315. self._options.onCancel(id, fileName);
  316. }
  317. });
  318. return handler;
  319. },
  320. _preventLeaveInProgress: function(){
  321. var self = this;
  322. qq.attach(window, 'beforeunload', function(e){
  323. if (!self._filesInProgress){return;}
  324. var e = e || window.event;
  325. // for ie, ff
  326. e.returnValue = self._options.messages.onLeave;
  327. // for webkit
  328. return self._options.messages.onLeave;
  329. });
  330. },
  331. _onSubmit: function(id, fileName){
  332. this._filesInProgress++;
  333. },
  334. _onProgress: function(id, fileName, loaded, total){
  335. },
  336. _onComplete: function(id, fileName, result){
  337. this._filesInProgress--;
  338. if (result.error){
  339. this._options.showMessage(result.error);
  340. }
  341. },
  342. _onCancel: function(id, fileName){
  343. this._filesInProgress--;
  344. },
  345. _onInputChange: function(input){
  346. if (this._handler instanceof qq.UploadHandlerXhr){
  347. this._uploadFileList(input.files);
  348. } else {
  349. if (this._validateFile(input)){
  350. this._uploadFile(input);
  351. }
  352. }
  353. this._button.reset();
  354. },
  355. _uploadFileList: function(files){
  356. for (var i=0; i<files.length; i++){
  357. if ( !this._validateFile(files[i])){
  358. return;
  359. }
  360. }
  361. for (var i=0; i<files.length; i++){
  362. this._uploadFile(files[i]);
  363. }
  364. },
  365. _uploadFile: function(fileContainer){
  366. var id = this._handler.add(fileContainer);
  367. var fileName = this._handler.getName(id);
  368. if (this._options.onSubmit(id, fileName) !== false){
  369. this._onSubmit(id, fileName);
  370. this._handler.upload(id, this._options.params);
  371. }
  372. },
  373. _validateFile: function(file){
  374. var name, size;
  375. if (file.value){
  376. // it is a file input
  377. // get input value and remove path to normalize
  378. name = file.value.replace(/.*(\/|\\)/, "");
  379. } else {
  380. // fix missing properties in Safari
  381. name = file.fileName != null ? file.fileName : file.name;
  382. size = file.fileSize != null ? file.fileSize : file.size;
  383. }
  384. if (! this._isAllowedExtension(name)){
  385. this._error('typeError', name);
  386. return false;
  387. } else if (size === 0){
  388. this._error('emptyError', name);
  389. return false;
  390. } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
  391. this._error('sizeError', name);
  392. return false;
  393. } else if (size && size < this._options.minSizeLimit){
  394. this._error('minSizeError', name);
  395. return false;
  396. }
  397. return true;
  398. },
  399. _error: function(code, fileName){
  400. var message = this._options.messages[code];
  401. function r(name, replacement){ message = message.replace(name, replacement); }
  402. r('{file}', this._formatFileName(fileName));
  403. r('{extensions}', this._options.allowedExtensions.join(', '));
  404. r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
  405. r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
  406. this._options.showMessage(message);
  407. },
  408. _formatFileName: function(name){
  409. if (name.length > 33){
  410. name = name.slice(0, 19) + '...' + name.slice(-13);
  411. }
  412. return name;
  413. },
  414. _isAllowedExtension: function(fileName){
  415. var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
  416. var allowed = this._options.allowedExtensions;
  417. if (!allowed.length){return true;}
  418. for (var i=0; i<allowed.length; i++){
  419. if (allowed[i].toLowerCase() == ext){ return true;}
  420. }
  421. return false;
  422. },
  423. _formatSize: function(bytes){
  424. var i = -1;
  425. do {
  426. bytes = bytes / 1024;
  427. i++;
  428. } while (bytes > 99);
  429. return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
  430. }
  431. };
  432. /**
  433. * Class that creates upload widget with drag-and-drop and file list
  434. * @inherits qq.FileUploaderBasic
  435. */
  436. qq.FileUploader = function(o){
  437. // call parent constructor
  438. qq.FileUploaderBasic.apply(this, arguments);
  439. // additional options
  440. qq.extend(this._options, {
  441. element: null,
  442. // if set, will be used instead of qq-upload-list in template
  443. listElement: null,
  444. template: '<div class="qq-uploader">' +
  445. '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
  446. '<div class="qq-upload-button">Upload a file</div>' +
  447. '<ul class="qq-upload-list"></ul>' +
  448. '</div>',
  449. // template for one item in file list
  450. fileTemplate: '<li>' +
  451. '<span class="qq-upload-file"></span>' +
  452. '<span class="qq-upload-spinner"></span>' +
  453. '<span class="qq-upload-size"></span>' +
  454. '<a class="qq-upload-cancel" href="#">Cancel</a>' +
  455. '<span class="qq-upload-failed-text">Failed</span>' +
  456. '</li>',
  457. classes: {
  458. // used to get elements from templates
  459. button: 'qq-upload-button',
  460. drop: 'qq-upload-drop-area',
  461. dropActive: 'qq-upload-drop-area-active',
  462. list: 'qq-upload-list',
  463. file: 'qq-upload-file',
  464. spinner: 'qq-upload-spinner',
  465. size: 'qq-upload-size',
  466. cancel: 'qq-upload-cancel',
  467. // added to list item when upload completes
  468. // used in css to hide progress spinner
  469. success: 'qq-upload-success',
  470. fail: 'qq-upload-fail'
  471. }
  472. });
  473. // overwrite options with user supplied
  474. this._options.dest = "";
  475. this._options.fileFieldLabel = "";
  476. qq.extend(this._options, o);
  477. this._element = this._options.element;
  478. this._element.innerHTML = this._options.template;
  479. this._listElement = this._options.listElement || this._find(this._element, 'list');
  480. this._classes = this._options.classes;
  481. this._button = this._createUploadButton(this._find(this._element, 'button'));
  482. this._bindCancelEvent();
  483. this._setupDragDrop();
  484. };
  485. // inherit from Basic Uploader
  486. qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);
  487. qq.extend(qq.FileUploader.prototype, {
  488. /**
  489. * Gets one of the elements listed in this._options.classes
  490. **/
  491. _find: function(parent, type){
  492. var element = qq.getByClass(parent, this._options.classes[type])[0];
  493. if (!element){
  494. throw new Error('element not found ' + type);
  495. }
  496. return element;
  497. },
  498. _setupDragDrop: function(){
  499. var self = this,
  500. dropArea = this._find(this._element, 'drop');
  501. var dz = new qq.UploadDropZone({
  502. element: dropArea,
  503. onEnter: function(e){
  504. qq.addClass(dropArea, self._classes.dropActive);
  505. e.stopPropagation();
  506. },
  507. onLeave: function(e){
  508. e.stopPropagation();
  509. },
  510. onLeaveNotDescendants: function(e){
  511. qq.removeClass(dropArea, self._classes.dropActive);
  512. },
  513. onDrop: function(e){
  514. dropArea.style.display = 'none';
  515. qq.removeClass(dropArea, self._classes.dropActive);
  516. self._uploadFileList(e.dataTransfer.files);
  517. }
  518. });
  519. dropArea.style.display = 'none';
  520. qq.attach(document, 'dragenter', function(e){
  521. if (!dz._isValidFileDrag(e)) return;
  522. dropArea.style.display = 'block';
  523. });
  524. qq.attach(document, 'dragleave', function(e){
  525. if (!dz._isValidFileDrag(e)) return;
  526. var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
  527. // only fire when leaving document out
  528. if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){
  529. dropArea.style.display = 'none';
  530. }
  531. });
  532. },
  533. _onSubmit: function(id, fileName){
  534. qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
  535. this._addToList(id, fileName);
  536. },
  537. _onProgress: function(id, fileName, loaded, total){
  538. qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);
  539. var item = this._getItemByFileId(id);
  540. var size = this._find(item, 'size');
  541. size.style.display = 'inline';
  542. var text;
  543. if (loaded != total){
  544. text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total);
  545. } else {
  546. text = this._formatSize(total);
  547. }
  548. qq.setText(size, text);
  549. },
  550. _onComplete: function(id, fileName, result){
  551. qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
  552. // mark completed
  553. var item = this._getItemByFileId(id);
  554. qq.remove(this._find(item, 'cancel'));
  555. qq.remove(this._find(item, 'spinner'));
  556. console.log(result)
  557. // if (result.success){
  558. qq.addClass(item, this._classes.success);
  559. /*} else {
  560. qq.addClass(item, this._classes.fail);
  561. }*/
  562. },
  563. _addToList: function(id, fileName){
  564. var item = qq.toElement(this._options.fileTemplate);
  565. item.qqFileId = id;
  566. var fileElement = this._find(item, 'file');
  567. qq.setText(fileElement, this._formatFileName(fileName));
  568. this._find(item, 'size').style.display = 'none';
  569. this._listElement.appendChild(item);
  570. },
  571. _getItemByFileId: function(id){
  572. var item = this._listElement.firstChild;
  573. // there can't be txt nodes in dynamically created list
  574. // and we can use nextSibling
  575. while (item){
  576. if (item.qqFileId == id) return item;
  577. item = item.nextSibling;
  578. }
  579. },
  580. /**
  581. * delegate click event for cancel link
  582. **/
  583. _bindCancelEvent: function(){
  584. var self = this,
  585. list = this._listElement;
  586. qq.attach(list, 'click', function(e){
  587. e = e || window.event;
  588. var target = e.target || e.srcElement;
  589. if (qq.hasClass(target, self._classes.cancel)){
  590. qq.preventDefault(e);
  591. var item = target.parentNode;
  592. self._handler.cancel(item.qqFileId);
  593. qq.remove(item);
  594. }
  595. });
  596. }
  597. });
  598. qq.UploadDropZone = function(o){
  599. this._options = {
  600. element: null,
  601. onEnter: function(e){},
  602. onLeave: function(e){},
  603. // is not fired when leaving element by hovering descendants
  604. onLeaveNotDescendants: function(e){},
  605. onDrop: function(e){}
  606. };
  607. qq.extend(this._options, o);
  608. this._element = this._options.element;
  609. this._disableDropOutside();
  610. this._attachEvents();
  611. };
  612. qq.UploadDropZone.prototype = {
  613. _disableDropOutside: function(e){
  614. // run only once for all instances
  615. if (!qq.UploadDropZone.dropOutsideDisabled ){
  616. qq.attach(document, 'dragover', function(e){
  617. if (e.dataTransfer){
  618. e.dataTransfer.dropEffect = 'none';
  619. e.preventDefault();
  620. }
  621. });
  622. qq.UploadDropZone.dropOutsideDisabled = true;
  623. }
  624. },
  625. _attachEvents: function(){
  626. var self = this;
  627. qq.attach(self._element, 'dragover', function(e){
  628. if (!self._isValidFileDrag(e)) return;
  629. var effect = e.dataTransfer.effectAllowed;
  630. if (effect == 'move' || effect == 'linkMove'){
  631. e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
  632. } else {
  633. e.dataTransfer.dropEffect = 'copy'; // for Chrome
  634. }
  635. e.stopPropagation();
  636. e.preventDefault();
  637. });
  638. qq.attach(self._element, 'dragenter', function(e){
  639. if (!self._isValidFileDrag(e)) return;
  640. self._options.onEnter(e);
  641. });
  642. qq.attach(self._element, 'dragleave', function(e){
  643. if (!self._isValidFileDrag(e)) return;
  644. self._options.onLeave(e);
  645. var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
  646. // do not fire when moving a mouse over a descendant
  647. if (qq.contains(this, relatedTarget)) return;
  648. self._options.onLeaveNotDescendants(e);
  649. });
  650. qq.attach(self._element, 'drop', function(e){
  651. if (!self._isValidFileDrag(e)) return;
  652. e.preventDefault();
  653. self._options.onDrop(e);
  654. });
  655. },
  656. _isValidFileDrag: function(e){
  657. var dt = e.dataTransfer,
  658. // do not check dt.types.contains in webkit, because it crashes safari 4
  659. isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;
  660. // dt.effectAllowed is none in Safari 5
  661. // dt.types.contains check is for firefox
  662. return dt && dt.effectAllowed != 'none' &&
  663. (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));
  664. }
  665. };
  666. qq.UploadButton = function(o){
  667. this._options = {
  668. element: null,
  669. // if set to true adds multiple attribute to file input
  670. multiple: false,
  671. // name attribute of file input
  672. name: 'file',
  673. onChange: function(input){},
  674. hoverClass: 'qq-upload-button-hover',
  675. focusClass: 'qq-upload-button-focus'
  676. };
  677. qq.extend(this._options, o);
  678. this._element = this._options.element;
  679. // make button suitable container for input
  680. qq.css(this._element, {
  681. position: 'relative',
  682. overflow: 'hidden',
  683. // Make sure browse button is in the right side
  684. // in Internet Explorer
  685. direction: 'ltr'
  686. });
  687. this._input = this._createInput();
  688. };
  689. qq.UploadButton.prototype = {
  690. /* returns file input element */
  691. getInput: function(){
  692. return this._input;
  693. },
  694. /* cleans/recreates the file input */
  695. reset: function(){
  696. if (this._input.parentNode){
  697. qq.remove(this._input);
  698. }
  699. qq.removeClass(this._element, this._options.focusClass);
  700. this._input = this._createInput();
  701. },
  702. _createInput: function(){
  703. var input = document.createElement("input");
  704. if (this._options.multiple){
  705. input.setAttribute("multiple", "multiple");
  706. }
  707. input.setAttribute("type", "file");
  708. input.setAttribute("name", this._options.name);
  709. qq.css(input, {
  710. position: 'absolute',
  711. // in Opera only 'browse' button
  712. // is clickable and it is located at
  713. // the right side of the input
  714. right: 0,
  715. top: 0,
  716. fontFamily: 'Arial',
  717. // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
  718. fontSize: '118px',
  719. margin: 0,
  720. padding: 0,
  721. cursor: 'pointer',
  722. opacity: 0
  723. });
  724. this._element.appendChild(input);
  725. var self = this;
  726. qq.attach(input, 'change', function(){
  727. self._options.onChange(input);
  728. });
  729. qq.attach(input, 'mouseover', function(){
  730. qq.addClass(self._element, self._options.hoverClass);
  731. });
  732. qq.attach(input, 'mouseout', function(){
  733. qq.removeClass(self._element, self._options.hoverClass);
  734. });
  735. qq.attach(input, 'focus', function(){
  736. qq.addClass(self._element, self._options.focusClass);
  737. });
  738. qq.attach(input, 'blur', function(){
  739. qq.removeClass(self._element, self._options.focusClass);
  740. });
  741. // IE and Opera, unfortunately have 2 tab stops on file input
  742. // which is unacceptable in our case, disable keyboard access
  743. if (window.attachEvent){
  744. // it is IE or Opera
  745. input.setAttribute('tabIndex', "-1");
  746. }
  747. return input;
  748. }
  749. };
  750. /**
  751. * Class for uploading files, uploading itself is handled by child classes
  752. */
  753. qq.UploadHandlerAbstract = function(o){
  754. this._options = {
  755. debug: false,
  756. action: '/upload.php',
  757. // maximum number of concurrent uploads
  758. maxConnections: 999,
  759. onProgress: function(id, fileName, loaded, total){},
  760. onComplete: function(id, fileName, response){},
  761. onCancel: function(id, fileName){}
  762. };
  763. qq.extend(this._options, o);
  764. this._queue = [];
  765. // params for files in queue
  766. this._params = [];
  767. };
  768. qq.UploadHandlerAbstract.prototype = {
  769. log: function(str){
  770. if (this._options.debug && window.console) console.log('[uploader] ' + str);
  771. },
  772. /**
  773. * Adds file or file input to the queue
  774. * @returns id
  775. **/
  776. add: function(file){},
  777. /**
  778. * Sends the file identified by id and additional query params to the server
  779. */
  780. upload: function(id, params){
  781. var len = this._queue.push(id);
  782. var copy = {};
  783. qq.extend(copy, params);
  784. this._params[id] = copy;
  785. // if too many active uploads, wait...
  786. if (len <= this._options.maxConnections){
  787. this._upload(id, this._params[id]);
  788. }
  789. },
  790. /**
  791. * Cancels file upload by id
  792. */
  793. cancel: function(id){
  794. this._cancel(id);
  795. this._dequeue(id);
  796. },
  797. /**
  798. * Cancells all uploads
  799. */
  800. cancelAll: function(){
  801. for (var i=0; i<this._queue.length; i++){
  802. this._cancel(this._queue[i]);
  803. }
  804. this._queue = [];
  805. },
  806. /**
  807. * Returns name of the file identified by id
  808. */
  809. getName: function(id){},
  810. /**
  811. * Returns size of the file identified by id
  812. */
  813. getSize: function(id){},
  814. /**
  815. * Returns id of files being uploaded or
  816. * waiting for their turn
  817. */
  818. getQueue: function(){
  819. return this._queue;
  820. },
  821. /**
  822. * Actual upload method
  823. */
  824. _upload: function(id){},
  825. /**
  826. * Actual cancel method
  827. */
  828. _cancel: function(id){},
  829. /**
  830. * Removes element from queue, starts upload of next
  831. */
  832. _dequeue: function(id){
  833. var i = qq.indexOf(this._queue, id);
  834. this._queue.splice(i, 1);
  835. var max = this._options.maxConnections;
  836. if (this._queue.length >= max && i < max){
  837. var nextId = this._queue[max-1];
  838. this._upload(nextId, this._params[nextId]);
  839. }
  840. }
  841. };
  842. /**
  843. * Class for uploading files using form and iframe
  844. * @inherits qq.UploadHandlerAbstract
  845. */
  846. qq.UploadHandlerForm = function(o){
  847. qq.UploadHandlerAbstract.apply(this, arguments);
  848. this._inputs = {};
  849. };
  850. // @inherits qq.UploadHandlerAbstract
  851. qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);
  852. qq.extend(qq.UploadHandlerForm.prototype, {
  853. add: function(fileInput){
  854. fileInput.setAttribute('name', 'qqfile');
  855. var id = 'qq-upload-handler-iframe' + qq.getUniqueId();
  856. this._inputs[id] = fileInput;
  857. // remove file input from DOM
  858. if (fileInput.parentNode){
  859. qq.remove(fileInput);
  860. }
  861. return id;
  862. },
  863. getName: function(id){
  864. // get input value and remove path to normalize
  865. return this._inputs[id].value.replace(/.*(\/|\\)/, "");
  866. },
  867. _cancel: function(id){
  868. this._options.onCancel(id, this.getName(id));
  869. delete this._inputs[id];
  870. var iframe = document.getElementById(id);
  871. if (iframe){
  872. // to cancel request set src to something else
  873. // we use src="javascript:false;" because it doesn't
  874. // trigger ie6 prompt on https
  875. iframe.setAttribute('src', 'javascript:false;');
  876. qq.remove(iframe);
  877. }
  878. },
  879. _upload: function(id, params){
  880. var input = this._inputs[id];
  881. if (!input){
  882. throw new Error('file with passed id was not added, or already uploaded or cancelled');
  883. }
  884. var fileName = this.getName(id);
  885. var iframe = this._createIframe(id);
  886. var form = this._createForm(iframe, params);
  887. input.name = params.fileFieldLabel;
  888. form.appendChild(input);
  889. var dest = document.createElement('input');
  890. dest.type = 'text';
  891. dest.name = 'dest';
  892. dest.value = params.dest;
  893. form.appendChild(dest);
  894. var self = this;
  895. this._attachLoadEvent(iframe, function(){
  896. self.log('iframe loaded');
  897. var response = self._getIframeContentJSON(iframe);
  898. self._options.onComplete(id, fileName, response);
  899. self._dequeue(id);
  900. delete self._inputs[id];
  901. // timeout added to fix busy state in FF3.6
  902. setTimeout(function(){
  903. qq.remove(iframe);
  904. }, 1);
  905. });
  906. form.submit();
  907. qq.remove(form);
  908. return id;
  909. },
  910. _attachLoadEvent: function(iframe, callback){
  911. qq.attach(iframe, 'load', function(){
  912. // when we remove iframe from dom
  913. // the request stops, but in IE load
  914. // event fires
  915. if (!iframe.parentNode){
  916. return;
  917. }
  918. // fixing Opera 10.53
  919. if (iframe.contentDocument &&
  920. iframe.contentDocument.body &&
  921. iframe.contentDocument.body.innerHTML == "false"){
  922. // In Opera event is fired second time
  923. // when body.innerHTML changed from false
  924. // to server response approx. after 1 sec
  925. // when we upload file with iframe
  926. return;
  927. }
  928. callback();
  929. });
  930. },
  931. /**
  932. * Returns json object received by iframe from server.
  933. */
  934. _getIframeContentJSON: function(iframe){
  935. // iframe.contentWindow.document - for IE<7
  936. var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
  937. response;
  938. this.log("converting iframe's innerHTML to JSON");
  939. this.log("innerHTML = " + doc.body.innerHTML);
  940. try {
  941. response = eval("(" + doc.body.innerHTML + ")");
  942. } catch(err){
  943. response = {};
  944. }
  945. return response;
  946. },
  947. /**
  948. * Creates iframe with unique name
  949. */
  950. _createIframe: function(id){
  951. // We can't use following code as the name attribute
  952. // won't be properly registered in IE6, and new window
  953. // on form submit will open
  954. // var iframe = document.createElement('iframe');
  955. // iframe.setAttribute('name', id);
  956. var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
  957. // src="javascript:false;" removes ie6 prompt on https
  958. iframe.setAttribute('id', id);
  959. iframe.style.display = 'none';
  960. document.body.appendChild(iframe);
  961. return iframe;
  962. },
  963. /**
  964. * Creates form, that will be submitted to iframe
  965. */
  966. _createForm: function(iframe, params){
  967. // We can't use the following code in IE6
  968. // var form = document.createElement('form');
  969. // form.setAttribute('method', 'post');
  970. // form.setAttribute('enctype', 'multipart/form-data');
  971. // Because in this case file won't be attached to request
  972. var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');
  973. form.setAttribute('action', this._options.action);
  974. form.setAttribute('target', iframe.name);
  975. form.style.display = 'none';
  976. document.body.appendChild(form);
  977. return form;
  978. }
  979. });
  980. /**
  981. * Class for uploading files using xhr
  982. * @inherits qq.UploadHandlerAbstract
  983. */
  984. qq.UploadHandlerXhr = function(o){
  985. qq.UploadHandlerAbstract.apply(this, arguments);
  986. this._files = [];
  987. this._xhrs = [];
  988. // current loaded size in bytes for each file
  989. this._loaded = [];
  990. };
  991. // static method
  992. qq.UploadHandlerXhr.isSupported = function(){
  993. var input = document.createElement('input');
  994. input.type = 'file';
  995. return (
  996. 'multiple' in input &&
  997. typeof File != "undefined" &&
  998. typeof (new XMLHttpRequest()).upload != "undefined" );
  999. };
  1000. // @inherits qq.UploadHandlerAbstract
  1001. qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype)
  1002. qq.extend(qq.UploadHandlerXhr.prototype, {
  1003. /**
  1004. * Adds file to the queue
  1005. * Returns id to use with upload, cancel
  1006. **/
  1007. add: function(file){
  1008. // HUE-815: [fb] Upload button does not work in Firefox 3.6
  1009. // see https://github.com/valums/ajax-upload/issues/91
  1010. //if (!(file instanceof File)){
  1011. if (!(file instanceof File || file.__proto__.constructor.name == 'File' || file instanceof Object) ){
  1012. throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
  1013. }
  1014. return this._files.push(file) - 1;
  1015. },
  1016. getName: function(id){
  1017. var file = this._files[id];
  1018. // fix missing name in Safari 4
  1019. return file.fileName != null ? file.fileName : file.name;
  1020. },
  1021. getSize: function(id){
  1022. var file = this._files[id];
  1023. return file.fileSize != null ? file.fileSize : file.size;
  1024. },
  1025. /**
  1026. * Returns uploaded bytes for file identified by id
  1027. */
  1028. getLoaded: function(id){
  1029. return this._loaded[id] || 0;
  1030. },
  1031. /**
  1032. * Sends the file identified by id and additional query params to the server
  1033. * @param {Object} params name-value string pairs
  1034. */
  1035. _upload: function(id, params){
  1036. var file = this._files[id],
  1037. name = this.getName(id),
  1038. size = this.getSize(id);
  1039. this._loaded[id] = 0;
  1040. var xhr = this._xhrs[id] = new XMLHttpRequest();
  1041. var self = this;
  1042. xhr.upload.onprogress = function(e){
  1043. if (e.lengthComputable){
  1044. self._loaded[id] = e.loaded;
  1045. self._options.onProgress(id, name, e.loaded, e.total);
  1046. }
  1047. };
  1048. xhr.onreadystatechange = function(){
  1049. if (xhr.readyState == 4){
  1050. self._onComplete(id, xhr);
  1051. }
  1052. };
  1053. var formData = new FormData();
  1054. formData.append(params.fileFieldLabel, file);
  1055. formData.append('dest', params.dest);
  1056. xhr.open("POST", this._options.action, true);
  1057. xhr.send(formData);
  1058. },
  1059. _onComplete: function(id, xhr){
  1060. // the request was aborted/cancelled
  1061. if (!this._files[id]) return;
  1062. var name = this.getName(id);
  1063. var size = this.getSize(id);
  1064. this._options.onProgress(id, name, size, size);
  1065. if (xhr.status == 200){
  1066. this.log("xhr - server response received");
  1067. this.log("responseText = " + xhr.responseText);
  1068. var response;
  1069. try {
  1070. response = eval("(" + xhr.responseText + ")");
  1071. } catch(err){
  1072. response = {};
  1073. }
  1074. this._options.onComplete(id, name, response);
  1075. } else {
  1076. this._options.onComplete(id, name, {});
  1077. }
  1078. this._files[id] = null;
  1079. this._xhrs[id] = null;
  1080. this._dequeue(id);
  1081. },
  1082. _cancel: function(id){
  1083. this._options.onCancel(id, this.getName(id));
  1084. this._files[id] = null;
  1085. if (this._xhrs[id]){
  1086. this._xhrs[id].abort();
  1087. this._xhrs[id] = null;
  1088. }
  1089. }
  1090. });