暂无描述

fileuploader.js 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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.substr(fileName.lastIndexOf('.')).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. window.FormData !== undefined
  976. };
  977. // @inherits qq.UploadHandlerAbstract
  978. qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype)
  979. qq.extend(qq.UploadHandlerXhr.prototype, {
  980. /**
  981. * Adds file to the queue
  982. * Returns id to use with upload, cancel
  983. **/
  984. add: function(file){
  985. if (!(file instanceof File)){
  986. throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
  987. }
  988. return this._files.push(file) - 1;
  989. },
  990. getName: function(id){
  991. var file = this._files[id];
  992. // fix missing name in Safari 4
  993. return file.fileName != null ? file.fileName : file.name;
  994. },
  995. getSize: function(id){
  996. var file = this._files[id];
  997. return file.fileSize != null ? file.fileSize : file.size;
  998. },
  999. /**
  1000. * Returns uploaded bytes for file identified by id
  1001. */
  1002. getLoaded: function(id){
  1003. return this._loaded[id] || 0;
  1004. },
  1005. /**
  1006. * Sends the file identified by id and additional query params to the server
  1007. * @param {Object} params name-value string pairs
  1008. */
  1009. _upload: function(id, params){
  1010. var file = this._files[id],
  1011. name = this.getName(id),
  1012. size = this.getSize(id);
  1013. this._loaded[id] = 0;
  1014. var xhr = this._xhrs[id] = new XMLHttpRequest();
  1015. var self = this;
  1016. xhr.upload.onprogress = function(e){
  1017. if (e.lengthComputable){
  1018. self._loaded[id] = e.loaded;
  1019. self._options.onProgress(id, name, e.loaded, e.total);
  1020. }
  1021. };
  1022. xhr.onreadystatechange = function(){
  1023. if (xhr.readyState == 4){
  1024. self._onComplete(id, xhr);
  1025. }
  1026. };
  1027. // build query string
  1028. params = params || {};
  1029. var queryString = qq.obj2url(params, this._options.action);
  1030. // Django requires form-data for file upload handlers to work
  1031. var formData = new FormData();
  1032. formData.append('file', file);
  1033. formData.append('qqfile', name);
  1034. xhr.open("POST", queryString, true);
  1035. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  1036. xhr.send(formData);
  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. });