fileuploader.js 40 KB

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