fileuploader.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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. if(obj.hasOwnProperty(i) && typeof obj[i] != 'function') {
  203. add(obj[i], i);
  204. }
  205. }
  206. } else {
  207. uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
  208. }
  209. return uristrings.join(prefix)
  210. .replace(/^&/, '')
  211. .replace(/%20/g, '+');
  212. };
  213. //
  214. //
  215. // Uploader Classes
  216. //
  217. //
  218. var qq = qq || {};
  219. /**
  220. * Creates upload button, validates upload, but doesn't create file list or dd.
  221. */
  222. qq.FileUploaderBasic = function(o){
  223. this._options = {
  224. // set to true to see the server response
  225. debug: false,
  226. action: '/server/upload',
  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. maxConnections: this._options.maxConnections,
  291. onProgress: function(id, fileName, loaded, total){
  292. self._onProgress(id, fileName, loaded, total);
  293. self._options.onProgress(id, fileName, loaded, total);
  294. },
  295. onComplete: function(id, fileName, result){
  296. self._onComplete(id, fileName, result);
  297. self._options.onComplete(id, fileName, result);
  298. },
  299. onCancel: function(id, fileName){
  300. self._onCancel(id, fileName);
  301. self._options.onCancel(id, fileName);
  302. }
  303. });
  304. return handler;
  305. },
  306. _preventLeaveInProgress: function(){
  307. var self = this;
  308. qq.attach(window, 'beforeunload', function(e){
  309. if (!self._filesInProgress){return;}
  310. var e = e || window.event;
  311. // for ie, ff
  312. e.returnValue = self._options.messages.onLeave;
  313. // for webkit
  314. return self._options.messages.onLeave;
  315. });
  316. },
  317. _onSubmit: function(id, fileName){
  318. this._filesInProgress++;
  319. },
  320. _onProgress: function(id, fileName, loaded, total){
  321. },
  322. _onComplete: function(id, fileName, result){
  323. this._filesInProgress--;
  324. if (result.error){
  325. this._options.showMessage(result.error);
  326. }
  327. },
  328. _onCancel: function(id, fileName){
  329. this._filesInProgress--;
  330. },
  331. _onInputChange: function(input){
  332. if (this._handler instanceof qq.UploadHandlerXhr){
  333. this._uploadFileList(input.files);
  334. } else {
  335. if (this._validateFile(input)){
  336. this._uploadFile(input);
  337. }
  338. }
  339. this._button.reset();
  340. },
  341. _uploadFileList: function(files){
  342. for (var i=0; i<files.length; i++){
  343. if ( !this._validateFile(files[i])){
  344. return;
  345. }
  346. }
  347. for (var i=0; i<files.length; i++){
  348. this._uploadFile(files[i]);
  349. }
  350. },
  351. _uploadFile: function(fileContainer){
  352. var id = this._handler.add(fileContainer);
  353. var fileName = this._handler.getName(id);
  354. if (this._options.onSubmit(id, fileName) !== false){
  355. this._onSubmit(id, fileName);
  356. this._handler.upload(id, this._options.params);
  357. }
  358. },
  359. _validateFile: function(file){
  360. var name, size;
  361. if (file.value){
  362. // it is a file input
  363. // get input value and remove path to normalize
  364. name = file.value.replace(/.*(\/|\\)/, "");
  365. } else {
  366. // fix missing properties in Safari
  367. name = file.fileName != null ? file.fileName : file.name;
  368. size = file.fileSize != null ? file.fileSize : file.size;
  369. }
  370. if (! this._isAllowedExtension(name)){
  371. this._error('typeError', name);
  372. return false;
  373. } else if (size === 0){
  374. this._error('emptyError', name);
  375. return false;
  376. } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
  377. this._error('sizeError', name);
  378. return false;
  379. } else if (size && size < this._options.minSizeLimit){
  380. this._error('minSizeError', name);
  381. return false;
  382. }
  383. return true;
  384. },
  385. _error: function(code, fileName){
  386. var message = this._options.messages[code];
  387. function r(name, replacement){ message = message.replace(name, replacement); }
  388. r('{file}', this._formatFileName(fileName));
  389. r('{extensions}', this._options.allowedExtensions.join(', '));
  390. r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
  391. r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
  392. this._options.showMessage(message);
  393. },
  394. _formatFileName: function(name){
  395. if (name.length > 33){
  396. name = name.slice(0, 19) + '...' + name.slice(-13);
  397. }
  398. return name;
  399. },
  400. _isAllowedExtension: function(fileName){
  401. var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
  402. var allowed = this._options.allowedExtensions;
  403. if (!allowed.length){return true;}
  404. for (var i=0; i<allowed.length; i++){
  405. if (allowed[i].toLowerCase() == ext){ return true;}
  406. }
  407. return false;
  408. },
  409. _formatSize: function(bytes){
  410. var i = -1;
  411. do {
  412. bytes = bytes / 1024;
  413. i++;
  414. } while (bytes > 99);
  415. return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
  416. }
  417. };
  418. /**
  419. * Class that creates upload widget with drag-and-drop and file list
  420. * @inherits qq.FileUploaderBasic
  421. */
  422. qq.FileUploader = function(o){
  423. // call parent constructor
  424. qq.FileUploaderBasic.apply(this, arguments);
  425. // additional options
  426. qq.extend(this._options, {
  427. element: null,
  428. // if set, will be used instead of qq-upload-list in template
  429. listElement: null,
  430. template: '<div class="qq-uploader">' +
  431. '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
  432. '<div class="qq-upload-button">Upload a file</div>' +
  433. '<ul class="qq-upload-list"></ul>' +
  434. '</div>',
  435. // template for one item in file list
  436. fileTemplate: '<li>' +
  437. '<span class="qq-upload-file"></span>' +
  438. '<span class="qq-upload-spinner"></span>' +
  439. '<span class="qq-upload-size"></span>' +
  440. '<a class="qq-upload-cancel" href="#">Cancel</a>' +
  441. '<span class="qq-upload-failed-text">Failed</span>' +
  442. '</li>',
  443. classes: {
  444. // used to get elements from templates
  445. button: 'qq-upload-button',
  446. drop: 'qq-upload-drop-area',
  447. dropActive: 'qq-upload-drop-area-active',
  448. list: 'qq-upload-list',
  449. file: 'qq-upload-file',
  450. spinner: 'qq-upload-spinner',
  451. size: 'qq-upload-size',
  452. cancel: 'qq-upload-cancel',
  453. // added to list item when upload completes
  454. // used in css to hide progress spinner
  455. success: 'qq-upload-success',
  456. fail: 'qq-upload-fail'
  457. }
  458. });
  459. // overwrite options with user supplied
  460. qq.extend(this._options, o);
  461. this._element = this._options.element;
  462. this._element.innerHTML = this._options.template;
  463. this._listElement = this._options.listElement || this._find(this._element, 'list');
  464. this._classes = this._options.classes;
  465. this._button = this._createUploadButton(this._find(this._element, 'button'));
  466. this._bindCancelEvent();
  467. this._setupDragDrop();
  468. };
  469. // inherit from Basic Uploader
  470. qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);
  471. qq.extend(qq.FileUploader.prototype, {
  472. /**
  473. * Gets one of the elements listed in this._options.classes
  474. **/
  475. _find: function(parent, type){
  476. var element = qq.getByClass(parent, this._options.classes[type])[0];
  477. if (!element){
  478. throw new Error('element not found ' + type);
  479. }
  480. return element;
  481. },
  482. _setupDragDrop: function(){
  483. var self = this,
  484. dropArea = this._find(this._element, 'drop');
  485. var dz = new qq.UploadDropZone({
  486. element: dropArea,
  487. onEnter: function(e){
  488. qq.addClass(dropArea, self._classes.dropActive);
  489. e.stopPropagation();
  490. },
  491. onLeave: function(e){
  492. e.stopPropagation();
  493. },
  494. onLeaveNotDescendants: function(e){
  495. qq.removeClass(dropArea, self._classes.dropActive);
  496. },
  497. onDrop: function(e){
  498. dropArea.style.display = 'none';
  499. qq.removeClass(dropArea, self._classes.dropActive);
  500. self._uploadFileList(e.dataTransfer.files);
  501. }
  502. });
  503. dropArea.style.display = 'none';
  504. qq.attach(document, 'dragenter', function(e){
  505. if (!dz._isValidFileDrag(e)) return;
  506. dropArea.style.display = 'block';
  507. });
  508. qq.attach(document, 'dragleave', function(e){
  509. if (!dz._isValidFileDrag(e)) return;
  510. var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
  511. // only fire when leaving document out
  512. if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){
  513. dropArea.style.display = 'none';
  514. }
  515. });
  516. },
  517. _onSubmit: function(id, fileName){
  518. qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
  519. this._addToList(id, fileName);
  520. },
  521. _onProgress: function(id, fileName, loaded, total){
  522. qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);
  523. var item = this._getItemByFileId(id);
  524. var size = this._find(item, 'size');
  525. size.style.display = 'inline';
  526. var text;
  527. if (loaded != total){
  528. text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total);
  529. } else {
  530. text = this._formatSize(total);
  531. }
  532. qq.setText(size, text);
  533. },
  534. _onComplete: function(id, fileName, result){
  535. qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
  536. // mark completed
  537. var item = this._getItemByFileId(id);
  538. qq.remove(this._find(item, 'cancel'));
  539. qq.remove(this._find(item, 'spinner'));
  540. if (result.success){
  541. qq.addClass(item, this._classes.success);
  542. } else {
  543. qq.addClass(item, this._classes.fail);
  544. }
  545. },
  546. _addToList: function(id, fileName){
  547. var item = qq.toElement(this._options.fileTemplate);
  548. item.qqFileId = id;
  549. var fileElement = this._find(item, 'file');
  550. qq.setText(fileElement, this._formatFileName(fileName));
  551. this._find(item, 'size').style.display = 'none';
  552. this._listElement.appendChild(item);
  553. },
  554. _getItemByFileId: function(id){
  555. var item = this._listElement.firstChild;
  556. // there can't be txt nodes in dynamically created list
  557. // and we can use nextSibling
  558. while (item){
  559. if (item.qqFileId == id) return item;
  560. item = item.nextSibling;
  561. }
  562. },
  563. /**
  564. * delegate click event for cancel link
  565. **/
  566. _bindCancelEvent: function(){
  567. var self = this,
  568. list = this._listElement;
  569. qq.attach(list, 'click', function(e){
  570. e = e || window.event;
  571. var target = e.target || e.srcElement;
  572. if (qq.hasClass(target, self._classes.cancel)){
  573. qq.preventDefault(e);
  574. var item = target.parentNode;
  575. self._handler.cancel(item.qqFileId);
  576. qq.remove(item);
  577. }
  578. });
  579. }
  580. });
  581. qq.UploadDropZone = function(o){
  582. this._options = {
  583. element: null,
  584. onEnter: function(e){},
  585. onLeave: function(e){},
  586. // is not fired when leaving element by hovering descendants
  587. onLeaveNotDescendants: function(e){},
  588. onDrop: function(e){}
  589. };
  590. qq.extend(this._options, o);
  591. this._element = this._options.element;
  592. this._disableDropOutside();
  593. this._attachEvents();
  594. };
  595. qq.UploadDropZone.prototype = {
  596. _disableDropOutside: function(e){
  597. // run only once for all instances
  598. if (!qq.UploadDropZone.dropOutsideDisabled ){
  599. qq.attach(document, 'dragover', function(e){
  600. if (e.dataTransfer){
  601. e.dataTransfer.dropEffect = 'none';
  602. e.preventDefault();
  603. }
  604. });
  605. qq.UploadDropZone.dropOutsideDisabled = true;
  606. }
  607. },
  608. _attachEvents: function(){
  609. var self = this;
  610. qq.attach(self._element, 'dragover', function(e){
  611. if (!self._isValidFileDrag(e)) return;
  612. var effect = e.dataTransfer.effectAllowed;
  613. if (effect == 'move' || effect == 'linkMove'){
  614. e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
  615. } else {
  616. e.dataTransfer.dropEffect = 'copy'; // for Chrome
  617. }
  618. e.stopPropagation();
  619. e.preventDefault();
  620. });
  621. qq.attach(self._element, 'dragenter', function(e){
  622. if (!self._isValidFileDrag(e)) return;
  623. self._options.onEnter(e);
  624. });
  625. qq.attach(self._element, 'dragleave', function(e){
  626. if (!self._isValidFileDrag(e)) return;
  627. self._options.onLeave(e);
  628. var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
  629. // do not fire when moving a mouse over a descendant
  630. if (qq.contains(this, relatedTarget)) return;
  631. self._options.onLeaveNotDescendants(e);
  632. });
  633. qq.attach(self._element, 'drop', function(e){
  634. if (!self._isValidFileDrag(e)) return;
  635. e.preventDefault();
  636. self._options.onDrop(e);
  637. });
  638. },
  639. _isValidFileDrag: function(e){
  640. var dt = e.dataTransfer,
  641. // do not check dt.types.contains in webkit, because it crashes safari 4
  642. isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;
  643. // dt.effectAllowed is none in Safari 5
  644. // dt.types.contains check is for firefox
  645. return dt && dt.effectAllowed != 'none' &&
  646. (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));
  647. }
  648. };
  649. qq.UploadButton = function(o){
  650. this._options = {
  651. element: null,
  652. // if set to true adds multiple attribute to file input
  653. multiple: false,
  654. // name attribute of file input
  655. name: 'file',
  656. onChange: function(input){},
  657. hoverClass: 'qq-upload-button-hover',
  658. focusClass: 'qq-upload-button-focus'
  659. };
  660. qq.extend(this._options, o);
  661. this._element = this._options.element;
  662. // make button suitable container for input
  663. qq.css(this._element, {
  664. position: 'relative',
  665. overflow: 'hidden',
  666. // Make sure browse button is in the right side
  667. // in Internet Explorer
  668. direction: 'ltr'
  669. });
  670. this._input = this._createInput();
  671. };
  672. qq.UploadButton.prototype = {
  673. /* returns file input element */
  674. getInput: function(){
  675. return this._input;
  676. },
  677. /* cleans/recreates the file input */
  678. reset: function(){
  679. if (this._input.parentNode){
  680. qq.remove(this._input);
  681. }
  682. qq.removeClass(this._element, this._options.focusClass);
  683. this._input = this._createInput();
  684. },
  685. _createInput: function(){
  686. var input = document.createElement("input");
  687. if (this._options.multiple){
  688. input.setAttribute("multiple", "multiple");
  689. }
  690. input.setAttribute("type", "file");
  691. input.setAttribute("name", this._options.name);
  692. qq.css(input, {
  693. position: 'absolute',
  694. // in Opera only 'browse' button
  695. // is clickable and it is located at
  696. // the right side of the input
  697. right: 0,
  698. top: 0,
  699. fontFamily: 'Arial',
  700. // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
  701. fontSize: '118px',
  702. margin: 0,
  703. padding: 0,
  704. cursor: 'pointer',
  705. opacity: 0
  706. });
  707. this._element.appendChild(input);
  708. var self = this;
  709. qq.attach(input, 'change', function(){
  710. self._options.onChange(input);
  711. });
  712. qq.attach(input, 'mouseover', function(){
  713. qq.addClass(self._element, self._options.hoverClass);
  714. });
  715. qq.attach(input, 'mouseout', function(){
  716. qq.removeClass(self._element, self._options.hoverClass);
  717. });
  718. qq.attach(input, 'focus', function(){
  719. qq.addClass(self._element, self._options.focusClass);
  720. });
  721. qq.attach(input, 'blur', function(){
  722. qq.removeClass(self._element, self._options.focusClass);
  723. });
  724. // IE and Opera, unfortunately have 2 tab stops on file input
  725. // which is unacceptable in our case, disable keyboard access
  726. if (window.attachEvent){
  727. // it is IE or Opera
  728. input.setAttribute('tabIndex', "-1");
  729. }
  730. return input;
  731. }
  732. };
  733. /**
  734. * Class for uploading files, uploading itself is handled by child classes
  735. */
  736. qq.UploadHandlerAbstract = function(o){
  737. this._options = {
  738. debug: false,
  739. action: '/upload.php',
  740. // maximum number of concurrent uploads
  741. maxConnections: 999,
  742. onProgress: function(id, fileName, loaded, total){},
  743. onComplete: function(id, fileName, response){},
  744. onCancel: function(id, fileName){}
  745. };
  746. qq.extend(this._options, o);
  747. this._queue = [];
  748. // params for files in queue
  749. this._params = [];
  750. };
  751. qq.UploadHandlerAbstract.prototype = {
  752. log: function(str){
  753. if (this._options.debug && window.console) console.log('[uploader] ' + str);
  754. },
  755. /**
  756. * Adds file or file input to the queue
  757. * @returns id
  758. **/
  759. add: function(file){},
  760. /**
  761. * Sends the file identified by id and additional query params to the server
  762. */
  763. upload: function(id, params){
  764. var len = this._queue.push(id);
  765. var copy = {};
  766. qq.extend(copy, params);
  767. this._params[id] = copy;
  768. // if too many active uploads, wait...
  769. if (len <= this._options.maxConnections){
  770. this._upload(id, this._params[id]);
  771. }
  772. },
  773. /**
  774. * Cancels file upload by id
  775. */
  776. cancel: function(id){
  777. this._cancel(id);
  778. this._dequeue(id);
  779. },
  780. /**
  781. * Cancells all uploads
  782. */
  783. cancelAll: function(){
  784. for (var i=0; i<this._queue.length; i++){
  785. this._cancel(this._queue[i]);
  786. }
  787. this._queue = [];
  788. },
  789. /**
  790. * Returns name of the file identified by id
  791. */
  792. getName: function(id){},
  793. /**
  794. * Returns size of the file identified by id
  795. */
  796. getSize: function(id){},
  797. /**
  798. * Returns id of files being uploaded or
  799. * waiting for their turn
  800. */
  801. getQueue: function(){
  802. return this._queue;
  803. },
  804. /**
  805. * Actual upload method
  806. */
  807. _upload: function(id){},
  808. /**
  809. * Actual cancel method
  810. */
  811. _cancel: function(id){},
  812. /**
  813. * Removes element from queue, starts upload of next
  814. */
  815. _dequeue: function(id){
  816. var i = qq.indexOf(this._queue, id);
  817. this._queue.splice(i, 1);
  818. var max = this._options.maxConnections;
  819. if (this._queue.length >= max && i < max){
  820. var nextId = this._queue[max-1];
  821. this._upload(nextId, this._params[nextId]);
  822. }
  823. }
  824. };
  825. /**
  826. * Class for uploading files using form and iframe
  827. * @inherits qq.UploadHandlerAbstract
  828. */
  829. qq.UploadHandlerForm = function(o){
  830. qq.UploadHandlerAbstract.apply(this, arguments);
  831. this._inputs = {};
  832. };
  833. // @inherits qq.UploadHandlerAbstract
  834. qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);
  835. qq.extend(qq.UploadHandlerForm.prototype, {
  836. add: function(fileInput){
  837. fileInput.setAttribute('name', 'qqfile');
  838. var id = 'qq-upload-handler-iframe' + qq.getUniqueId();
  839. this._inputs[id] = fileInput;
  840. // remove file input from DOM
  841. if (fileInput.parentNode){
  842. qq.remove(fileInput);
  843. }
  844. return id;
  845. },
  846. getName: function(id){
  847. // get input value and remove path to normalize
  848. return this._inputs[id].value.replace(/.*(\/|\\)/, "");
  849. },
  850. _cancel: function(id){
  851. this._options.onCancel(id, this.getName(id));
  852. delete this._inputs[id];
  853. var iframe = document.getElementById(id);
  854. if (iframe){
  855. // to cancel request set src to something else
  856. // we use src="javascript:false;" because it doesn't
  857. // trigger ie6 prompt on https
  858. iframe.setAttribute('src', 'javascript:false;');
  859. qq.remove(iframe);
  860. }
  861. },
  862. _upload: function(id, params){
  863. var input = this._inputs[id];
  864. if (!input){
  865. throw new Error('file with passed id was not added, or already uploaded or cancelled');
  866. }
  867. var fileName = this.getName(id);
  868. var iframe = this._createIframe(id);
  869. var form = this._createForm(iframe, params);
  870. form.appendChild(input);
  871. var self = this;
  872. this._attachLoadEvent(iframe, function(){
  873. self.log('iframe loaded');
  874. var response = self._getIframeContentJSON(iframe);
  875. self._options.onComplete(id, fileName, response);
  876. self._dequeue(id);
  877. delete self._inputs[id];
  878. // timeout added to fix busy state in FF3.6
  879. setTimeout(function(){
  880. qq.remove(iframe);
  881. }, 1);
  882. });
  883. form.submit();
  884. qq.remove(form);
  885. return id;
  886. },
  887. _attachLoadEvent: function(iframe, callback){
  888. qq.attach(iframe, 'load', function(){
  889. // when we remove iframe from dom
  890. // the request stops, but in IE load
  891. // event fires
  892. if (!iframe.parentNode){
  893. return;
  894. }
  895. // fixing Opera 10.53
  896. if (iframe.contentDocument &&
  897. iframe.contentDocument.body &&
  898. iframe.contentDocument.body.innerHTML == "false"){
  899. // In Opera event is fired second time
  900. // when body.innerHTML changed from false
  901. // to server response approx. after 1 sec
  902. // when we upload file with iframe
  903. return;
  904. }
  905. callback();
  906. });
  907. },
  908. /**
  909. * Returns json object received by iframe from server.
  910. */
  911. _getIframeContentJSON: function(iframe){
  912. // iframe.contentWindow.document - for IE<7
  913. var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
  914. response;
  915. this.log("converting iframe's innerHTML to JSON");
  916. this.log("innerHTML = " + doc.body.innerHTML);
  917. try {
  918. response = eval("(" + doc.body.innerHTML + ")");
  919. } catch(err){
  920. response = {};
  921. }
  922. return response;
  923. },
  924. /**
  925. * Creates iframe with unique name
  926. */
  927. _createIframe: function(id){
  928. // We can't use following code as the name attribute
  929. // won't be properly registered in IE6, and new window
  930. // on form submit will open
  931. // var iframe = document.createElement('iframe');
  932. // iframe.setAttribute('name', id);
  933. var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
  934. // src="javascript:false;" removes ie6 prompt on https
  935. iframe.setAttribute('id', id);
  936. iframe.style.display = 'none';
  937. document.body.appendChild(iframe);
  938. return iframe;
  939. },
  940. /**
  941. * Creates form, that will be submitted to iframe
  942. */
  943. _createForm: function(iframe, params){
  944. // We can't use the following code in IE6
  945. // var form = document.createElement('form');
  946. // form.setAttribute('method', 'post');
  947. // form.setAttribute('enctype', 'multipart/form-data');
  948. // Because in this case file won't be attached to request
  949. var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');
  950. var queryString = qq.obj2url(params, this._options.action);
  951. form.setAttribute('action', queryString);
  952. form.setAttribute('target', iframe.name);
  953. form.style.display = 'none';
  954. document.body.appendChild(form);
  955. return form;
  956. }
  957. });
  958. /**
  959. * Class for uploading files using xhr
  960. * @inherits qq.UploadHandlerAbstract
  961. */
  962. qq.UploadHandlerXhr = function(o){
  963. qq.UploadHandlerAbstract.apply(this, arguments);
  964. this._files = [];
  965. this._xhrs = [];
  966. // current loaded size in bytes for each file
  967. this._loaded = [];
  968. };
  969. // static method
  970. qq.UploadHandlerXhr.isSupported = function(){
  971. var input = document.createElement('input');
  972. input.type = 'file';
  973. return (
  974. 'multiple' in input &&
  975. typeof File != "undefined" &&
  976. typeof (new XMLHttpRequest()).upload != "undefined" );
  977. };
  978. // @inherits qq.UploadHandlerAbstract
  979. qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype);
  980. qq.extend(qq.UploadHandlerXhr.prototype, {
  981. /**
  982. * Adds file to the queue
  983. * Returns id to use with upload, cancel
  984. **/
  985. add: function(file){
  986. if (!(file instanceof File)){
  987. throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
  988. }
  989. return this._files.push(file) - 1;
  990. },
  991. getName: function(id){
  992. var file = this._files[id];
  993. // fix missing name in Safari 4
  994. return file.fileName != null ? file.fileName : file.name;
  995. },
  996. getSize: function(id){
  997. var file = this._files[id];
  998. return file.fileSize != null ? file.fileSize : file.size;
  999. },
  1000. /**
  1001. * Returns uploaded bytes for file identified by id
  1002. */
  1003. getLoaded: function(id){
  1004. return this._loaded[id] || 0;
  1005. },
  1006. /**
  1007. * Sends the file identified by id and additional query params to the server
  1008. * @param {Object} params name-value string pairs
  1009. */
  1010. _upload: function(id, params){
  1011. var file = this._files[id],
  1012. name = this.getName(id),
  1013. size = this.getSize(id);
  1014. this._loaded[id] = 0;
  1015. var xhr = this._xhrs[id] = new XMLHttpRequest();
  1016. var self = this;
  1017. xhr.upload.onprogress = function(e){
  1018. if (e.lengthComputable){
  1019. self._loaded[id] = e.loaded;
  1020. self._options.onProgress(id, name, e.loaded, e.total);
  1021. }
  1022. };
  1023. xhr.onreadystatechange = function(){
  1024. if (xhr.readyState == 4){
  1025. self._onComplete(id, xhr);
  1026. }
  1027. };
  1028. // build query string
  1029. params = params || {};
  1030. params['qqfile'] = name;
  1031. var queryString = qq.obj2url(params, this._options.action);
  1032. xhr.open("POST", queryString, true);
  1033. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  1034. xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
  1035. xhr.setRequestHeader("Content-Type", "application/octet-stream");
  1036. xhr.send(file);
  1037. },
  1038. _onComplete: function(id, xhr){
  1039. // the request was aborted/cancelled
  1040. if (!this._files[id]) return;
  1041. var name = this.getName(id);
  1042. var size = this.getSize(id);
  1043. this._options.onProgress(id, name, size, size);
  1044. if (xhr.status == 200){
  1045. this.log("xhr - server response received");
  1046. this.log("responseText = " + xhr.responseText);
  1047. var response;
  1048. try {
  1049. response = eval("(" + xhr.responseText + ")");
  1050. } catch(err){
  1051. response = {};
  1052. }
  1053. this._options.onComplete(id, name, response);
  1054. } else {
  1055. this._options.onComplete(id, name, {});
  1056. }
  1057. this._files[id] = null;
  1058. this._xhrs[id] = null;
  1059. this._dequeue(id);
  1060. },
  1061. _cancel: function(id){
  1062. this._options.onCancel(id, this.getName(id));
  1063. this._files[id] = null;
  1064. if (this._xhrs[id]){
  1065. this._xhrs[id].abort();
  1066. this._xhrs[id] = null;
  1067. }
  1068. }
  1069. });