fileuploader.js 39 KB

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