fileuploader.js 39 KB

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