plupload.dev.js 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  1. /**
  2. * Plupload - multi-runtime File Uploader
  3. * v2.0.0beta
  4. *
  5. * Copyright 2013, Moxiecode Systems AB
  6. * Released under GPL License.
  7. *
  8. * License: http://www.plupload.com/license
  9. * Contributing: http://www.plupload.com/contributing
  10. *
  11. * Date: 2012-11-30
  12. */
  13. /**
  14. * Plupload.js
  15. *
  16. * Copyright 2013, Moxiecode Systems AB
  17. * Released under GPL License.
  18. *
  19. * License: http://www.plupload.com/license
  20. * Contributing: http://www.plupload.com/contributing
  21. */
  22. /*global mOxie:true */
  23. ;(function(window, o, undef) {
  24. var delay = window.setTimeout
  25. , fileFilters = {}
  26. ;
  27. // convert plupload features to caps acceptable by mOxie
  28. function normalizeCaps(settings) {
  29. var features = settings.required_features, caps = {};
  30. function resolve(feature, value, strict) {
  31. // Feature notation is deprecated, use caps (this thing here is required for backward compatibility)
  32. var map = {
  33. chunks: 'slice_blob',
  34. resize: 'send_binary_string',
  35. jpgresize: 'send_binary_string',
  36. pngresize: 'send_binary_string',
  37. progress: 'report_upload_progress',
  38. multi_selection: 'select_multiple',
  39. max_file_size: 'access_binary',
  40. dragdrop: 'drag_and_drop',
  41. drop_element: 'drag_and_drop',
  42. headers: 'send_custom_headers',
  43. canSendBinary: 'send_binary',
  44. triggerDialog: 'summon_file_dialog'
  45. };
  46. if (map[feature]) {
  47. caps[map[feature]] = value;
  48. } else if (!strict) {
  49. caps[feature] = value;
  50. }
  51. }
  52. if (typeof(features) === 'string') {
  53. plupload.each(features.split(/\s*,\s*/), function(feature) {
  54. resolve(feature, true);
  55. });
  56. } else if (typeof(features) === 'object') {
  57. plupload.each(features, function(value, feature) {
  58. resolve(feature, value);
  59. });
  60. } else if (features === true) {
  61. // check settings for required features
  62. if (!settings.multipart) { // special care for multipart: false
  63. caps.send_binary_string = true;
  64. }
  65. if (settings.chunk_size > 0) {
  66. caps.slice_blob = true;
  67. }
  68. plupload.each(settings, function(value, feature) {
  69. resolve(feature, !!value, true); // strict check
  70. });
  71. }
  72. return caps;
  73. }
  74. /**
  75. * @module plupload
  76. * @static
  77. */
  78. var plupload = {
  79. /**
  80. * Plupload version will be replaced on build.
  81. *
  82. * @property VERSION
  83. * @for Plupload
  84. * @static
  85. * @final
  86. */
  87. VERSION : '2.0.0beta',
  88. /**
  89. * Inital state of the queue and also the state ones it's finished all it's uploads.
  90. *
  91. * @property STOPPED
  92. * @static
  93. * @final
  94. */
  95. STOPPED : 1,
  96. /**
  97. * Upload process is running
  98. *
  99. * @property STARTED
  100. * @static
  101. * @final
  102. */
  103. STARTED : 2,
  104. /**
  105. * File is queued for upload
  106. *
  107. * @property QUEUED
  108. * @static
  109. * @final
  110. */
  111. QUEUED : 1,
  112. /**
  113. * File is being uploaded
  114. *
  115. * @property UPLOADING
  116. * @static
  117. * @final
  118. */
  119. UPLOADING : 2,
  120. /**
  121. * File has failed to be uploaded
  122. *
  123. * @property FAILED
  124. * @static
  125. * @final
  126. */
  127. FAILED : 4,
  128. /**
  129. * File has been uploaded successfully
  130. *
  131. * @property DONE
  132. * @static
  133. * @final
  134. */
  135. DONE : 5,
  136. // Error constants used by the Error event
  137. /**
  138. * Generic error for example if an exception is thrown inside Silverlight.
  139. *
  140. * @property GENERIC_ERROR
  141. * @static
  142. * @final
  143. */
  144. GENERIC_ERROR : -100,
  145. /**
  146. * HTTP transport error. For example if the server produces a HTTP status other than 200.
  147. *
  148. * @property HTTP_ERROR
  149. * @static
  150. * @final
  151. */
  152. HTTP_ERROR : -200,
  153. /**
  154. * Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine.
  155. *
  156. * @property IO_ERROR
  157. * @static
  158. * @final
  159. */
  160. IO_ERROR : -300,
  161. /**
  162. * Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine.
  163. *
  164. * @property SECURITY_ERROR
  165. * @static
  166. * @final
  167. */
  168. SECURITY_ERROR : -400,
  169. /**
  170. * Initialization error. Will be triggered if no runtime was initialized.
  171. *
  172. * @property INIT_ERROR
  173. * @static
  174. * @final
  175. */
  176. INIT_ERROR : -500,
  177. /**
  178. * File size error. If the user selects a file that is too large it will be blocked and an error of this type will be triggered.
  179. *
  180. * @property FILE_SIZE_ERROR
  181. * @static
  182. * @final
  183. */
  184. FILE_SIZE_ERROR : -600,
  185. /**
  186. * File extension error. If the user selects a file that isn't valid according to the filters setting.
  187. *
  188. * @property FILE_EXTENSION_ERROR
  189. * @static
  190. * @final
  191. */
  192. FILE_EXTENSION_ERROR : -601,
  193. /**
  194. * Duplicate file error. If prevent_duplicates is set to true and user selects the same file again.
  195. *
  196. * @property FILE_DUPLICATE_ERROR
  197. * @static
  198. * @final
  199. */
  200. FILE_DUPLICATE_ERROR : -602,
  201. /**
  202. * Runtime will try to detect if image is proper one. Otherwise will throw this error.
  203. *
  204. * @property IMAGE_FORMAT_ERROR
  205. * @static
  206. * @final
  207. */
  208. IMAGE_FORMAT_ERROR : -700,
  209. /**
  210. * While working on the image runtime will try to detect if the operation may potentially run out of memeory and will throw this error.
  211. *
  212. * @property IMAGE_MEMORY_ERROR
  213. * @static
  214. * @final
  215. */
  216. IMAGE_MEMORY_ERROR : -701,
  217. /**
  218. * Each runtime has an upper limit on a dimension of the image it can handle. If bigger, will throw this error.
  219. *
  220. * @property IMAGE_DIMENSIONS_ERROR
  221. * @static
  222. * @final
  223. */
  224. IMAGE_DIMENSIONS_ERROR : -702,
  225. /**
  226. * Mime type lookup table.
  227. *
  228. * @property mimeTypes
  229. * @type Object
  230. * @final
  231. */
  232. mimeTypes : o.mimes,
  233. /**
  234. * In some cases sniffing is the only way around :(
  235. */
  236. ua: o.ua,
  237. /**
  238. * Gets the true type of the built-in object (better version of typeof).
  239. * @credits Angus Croll (http://javascriptweblog.wordpress.com/)
  240. *
  241. * @method typeOf
  242. * @static
  243. * @param {Object} o Object to check.
  244. * @return {String} Object [[Class]]
  245. */
  246. typeOf: o.typeOf,
  247. /**
  248. * Extends the specified object with another object.
  249. *
  250. * @method extend
  251. * @static
  252. * @param {Object} target Object to extend.
  253. * @param {Object..} obj Multiple objects to extend with.
  254. * @return {Object} Same as target, the extended object.
  255. */
  256. extend : o.extend,
  257. /**
  258. * Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers.
  259. * The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages
  260. * to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique.
  261. * It's more probable for the earth to be hit with an ansteriod. You can also if you want to be 100% sure set the plupload.guidPrefix property
  262. * to an user unique key.
  263. *
  264. * @method guid
  265. * @static
  266. * @return {String} Virtually unique id.
  267. */
  268. guid : o.guid,
  269. /**
  270. * Executes the callback function for each item in array/object. If you return false in the
  271. * callback it will break the loop.
  272. *
  273. * @method each
  274. * @static
  275. * @param {Object} obj Object to iterate.
  276. * @param {function} callback Callback function to execute for each item.
  277. */
  278. each : o.each,
  279. /**
  280. * Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
  281. *
  282. * @method getPos
  283. * @static
  284. * @param {Element} node HTML element or element id to get x, y position from.
  285. * @param {Element} root Optional root element to stop calculations at.
  286. * @return {object} Absolute position of the specified element object with x, y fields.
  287. */
  288. getPos : o.getPos,
  289. /**
  290. * Returns the size of the specified node in pixels.
  291. *
  292. * @method getSize
  293. * @static
  294. * @param {Node} node Node to get the size of.
  295. * @return {Object} Object with a w and h property.
  296. */
  297. getSize : o.getSize,
  298. /**
  299. * Encodes the specified string.
  300. *
  301. * @method xmlEncode
  302. * @static
  303. * @param {String} s String to encode.
  304. * @return {String} Encoded string.
  305. */
  306. xmlEncode : function(str) {
  307. var xmlEncodeChars = {'<' : 'lt', '>' : 'gt', '&' : 'amp', '"' : 'quot', '\'' : '#39'}, xmlEncodeRegExp = /[<>&\"\']/g;
  308. return str ? ('' + str).replace(xmlEncodeRegExp, function(chr) {
  309. return xmlEncodeChars[chr] ? '&' + xmlEncodeChars[chr] + ';' : chr;
  310. }) : str;
  311. },
  312. /**
  313. * Forces anything into an array.
  314. *
  315. * @method toArray
  316. * @static
  317. * @param {Object} obj Object with length field.
  318. * @return {Array} Array object containing all items.
  319. */
  320. toArray : o.toArray,
  321. /**
  322. * Find an element in array and return it's index if present, otherwise return -1.
  323. *
  324. * @method inArray
  325. * @static
  326. * @param {mixed} needle Element to find
  327. * @param {Array} array
  328. * @return {Int} Index of the element, or -1 if not found
  329. */
  330. inArray : o.inArray,
  331. /**
  332. * Extends the language pack object with new items.
  333. *
  334. * @method addI18n
  335. * @static
  336. * @param {Object} pack Language pack items to add.
  337. * @return {Object} Extended language pack object.
  338. */
  339. addI18n : o.addI18n,
  340. /**
  341. * Translates the specified string by checking for the english string in the language pack lookup.
  342. *
  343. * @method translate
  344. * @static
  345. * @param {String} str String to look for.
  346. * @return {String} Translated string or the input string if it wasn't found.
  347. */
  348. translate : o.translate,
  349. /**
  350. * Checks if object is empty.
  351. *
  352. * @method isEmptyObj
  353. * @static
  354. * @param {Object} obj Object to check.
  355. * @return {Boolean}
  356. */
  357. isEmptyObj : o.isEmptyObj,
  358. /**
  359. * Checks if specified DOM element has specified class.
  360. *
  361. * @method hasClass
  362. * @static
  363. * @param {Object} obj DOM element like object to add handler to.
  364. * @param {String} name Class name
  365. */
  366. hasClass : o.hasClass,
  367. /**
  368. * Adds specified className to specified DOM element.
  369. *
  370. * @method addClass
  371. * @static
  372. * @param {Object} obj DOM element like object to add handler to.
  373. * @param {String} name Class name
  374. */
  375. addClass : o.addClass,
  376. /**
  377. * Removes specified className from specified DOM element.
  378. *
  379. * @method removeClass
  380. * @static
  381. * @param {Object} obj DOM element like object to add handler to.
  382. * @param {String} name Class name
  383. */
  384. removeClass : o.removeClass,
  385. /**
  386. * Returns a given computed style of a DOM element.
  387. *
  388. * @method getStyle
  389. * @static
  390. * @param {Object} obj DOM element like object.
  391. * @param {String} name Style you want to get from the DOM element
  392. */
  393. getStyle : o.getStyle,
  394. /**
  395. * Adds an event handler to the specified object and store reference to the handler
  396. * in objects internal Plupload registry (@see removeEvent).
  397. *
  398. * @method addEvent
  399. * @static
  400. * @param {Object} obj DOM element like object to add handler to.
  401. * @param {String} name Name to add event listener to.
  402. * @param {Function} callback Function to call when event occurs.
  403. * @param {String} (optional) key that might be used to add specifity to the event record.
  404. */
  405. addEvent : o.addEvent,
  406. /**
  407. * Remove event handler from the specified object. If third argument (callback)
  408. * is not specified remove all events with the specified name.
  409. *
  410. * @method removeEvent
  411. * @static
  412. * @param {Object} obj DOM element to remove event listener(s) from.
  413. * @param {String} name Name of event listener to remove.
  414. * @param {Function|String} (optional) might be a callback or unique key to match.
  415. */
  416. removeEvent: o.removeEvent,
  417. /**
  418. * Remove all kind of events from the specified object
  419. *
  420. * @method removeAllEvents
  421. * @static
  422. * @param {Object} obj DOM element to remove event listeners from.
  423. * @param {String} (optional) unique key to match, when removing events.
  424. */
  425. removeAllEvents: o.removeAllEvents,
  426. /**
  427. * Cleans the specified name from national characters (diacritics). The result will be a name with only a-z, 0-9 and _.
  428. *
  429. * @method cleanName
  430. * @static
  431. * @param {String} s String to clean up.
  432. * @return {String} Cleaned string.
  433. */
  434. cleanName : function(name) {
  435. var i, lookup;
  436. // Replace diacritics
  437. lookup = [
  438. /[\300-\306]/g, 'A', /[\340-\346]/g, 'a',
  439. /\307/g, 'C', /\347/g, 'c',
  440. /[\310-\313]/g, 'E', /[\350-\353]/g, 'e',
  441. /[\314-\317]/g, 'I', /[\354-\357]/g, 'i',
  442. /\321/g, 'N', /\361/g, 'n',
  443. /[\322-\330]/g, 'O', /[\362-\370]/g, 'o',
  444. /[\331-\334]/g, 'U', /[\371-\374]/g, 'u'
  445. ];
  446. for (i = 0; i < lookup.length; i += 2) {
  447. name = name.replace(lookup[i], lookup[i + 1]);
  448. }
  449. // Replace whitespace
  450. name = name.replace(/\s+/g, '_');
  451. // Remove anything else
  452. name = name.replace(/[^a-z0-9_\-\.]+/gi, '');
  453. return name;
  454. },
  455. /**
  456. * Builds a full url out of a base URL and an object with items to append as query string items.
  457. *
  458. * @method buildUrl
  459. * @static
  460. * @param {String} url Base URL to append query string items to.
  461. * @param {Object} items Name/value object to serialize as a querystring.
  462. * @return {String} String with url + serialized query string items.
  463. */
  464. buildUrl : function(url, items) {
  465. var query = '';
  466. plupload.each(items, function(value, name) {
  467. query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value);
  468. });
  469. if (query) {
  470. url += (url.indexOf('?') > 0 ? '&' : '?') + query;
  471. }
  472. return url;
  473. },
  474. /**
  475. * Formats the specified number as a size string for example 1024 becomes 1 KB.
  476. *
  477. * @method formatSize
  478. * @static
  479. * @param {Number} size Size to format as string.
  480. * @return {String} Formatted size string.
  481. */
  482. formatSize : function(size) {
  483. if (size === undef || /\D/.test(size)) {
  484. return plupload.translate('N/A');
  485. }
  486. // TB
  487. if (size > 1099511627776) {
  488. return Math.round(size / 1099511627776, 1) + " " + plupload.translate('tb');
  489. }
  490. // GB
  491. if (size > 1073741824) {
  492. return Math.round(size / 1073741824, 1) + " " + plupload.translate('gb');
  493. }
  494. // MB
  495. if (size > 1048576) {
  496. return Math.round(size / 1048576, 1) + " " + plupload.translate('mb');
  497. }
  498. // KB
  499. if (size > 1024) {
  500. return Math.round(size / 1024, 1) + " " + plupload.translate('kb');
  501. }
  502. return size + " " + plupload.translate('b');
  503. },
  504. /**
  505. * Parses the specified size string into a byte value. For example 10kb becomes 10240.
  506. *
  507. * @method parseSize
  508. * @static
  509. * @param {String|Number} size String to parse or number to just pass through.
  510. * @return {Number} Size in bytes.
  511. */
  512. parseSize : o.parseSizeStr,
  513. /**
  514. * A way to predict what runtime will be choosen in the current environment with the
  515. * specified settings.
  516. *
  517. * @method predictRuntime
  518. * @static
  519. * @param {Object|String} config Plupload settings to check
  520. * @param {String} [runtimes] Comma-separated list of runtimes to check against
  521. * @return {String} Type of compatible runtime
  522. */
  523. predictRuntime : function(config, runtimes) {
  524. var up, runtime;
  525. if (runtimes) {
  526. config.runtimes = runtimes;
  527. }
  528. up = new plupload.Uploader(config);
  529. runtime = up.runtime;
  530. up.destroy();
  531. return runtime;
  532. },
  533. /**
  534. * Registers a filter that will be executed for each file added to the queue.
  535. * If callback returns false, file will not be added.
  536. *
  537. * Callback receives two arguments: a value for the filter as it was specified in settings.filters
  538. * and a file to be filtered. Callback is executed in the context of uploader instance.
  539. *
  540. * @method addFileFilter
  541. * @static
  542. * @param {String} name Name of the filter by which it can be referenced in settings.filters
  543. * @param {String} cb Callback - the actual routine that every added file must pass
  544. */
  545. addFileFilter: function(name, cb) {
  546. fileFilters[name] = cb;
  547. }
  548. };
  549. plupload.addFileFilter('mime_types', (function() {
  550. var _filters, _extRegExp;
  551. // Convert extensions to regexp
  552. function getExtRegExp(filters) {
  553. var extensionsRegExp = [];
  554. plupload.each(filters, function(filter) {
  555. plupload.each(filter.extensions.split(/,/), function(ext) {
  556. if (/^\s*\*\s*$/.test(ext)) {
  557. extensionsRegExp.push('\\.*');
  558. } else {
  559. extensionsRegExp.push('\\.' + ext.replace(new RegExp('[' + ('/^$.*+?|()[]{}\\'.replace(/./g, '\\$&')) + ']', 'g'), '\\$&'));
  560. }
  561. });
  562. });
  563. return new RegExp('(' + extensionsRegExp.join('|') + ')$', 'i');
  564. }
  565. return function(filters, file, cb) {
  566. if (!_extRegExp || filters != _filters) { // make sure we do it only once, unless filters got changed
  567. _extRegExp = getExtRegExp(filters);
  568. _filters = [].slice.call(filters);
  569. }
  570. if (!_extRegExp.test(file.name)) {
  571. this.trigger('Error', {
  572. code : plupload.FILE_EXTENSION_ERROR,
  573. message : plupload.translate('File extension error.'),
  574. file : file
  575. });
  576. cb(false);
  577. } else {
  578. cb(true);
  579. }
  580. };
  581. }()));
  582. plupload.addFileFilter('max_file_size', function(maxSize, file, cb) {
  583. var undef;
  584. // Invalid file size
  585. if (file.size !== undef && maxSize && file.size > maxSize) {
  586. this.trigger('Error', {
  587. code : plupload.FILE_SIZE_ERROR,
  588. message : plupload.translate('File size error.'),
  589. file : file
  590. });
  591. cb(false);
  592. } else {
  593. cb(true);
  594. }
  595. });
  596. plupload.addFileFilter('prevent_duplicates', function(value, file, cb) {
  597. if (value) {
  598. var ii = this.files.length;
  599. while (ii--) {
  600. // Compare by name and size (size might be 0 or undefined, but still equivalent for both)
  601. if (file.name === this.files[ii].name && file.size === this.files[ii].size) {
  602. this.trigger('Error', {
  603. code : plupload.FILE_DUPLICATE_ERROR,
  604. message : plupload.translate('Duplicate file error.'),
  605. file : file
  606. });
  607. cb(false);
  608. return;
  609. }
  610. }
  611. }
  612. cb(true);
  613. });
  614. /**
  615. @class Uploader
  616. @constructor
  617. @param {Object} settings For detailed information about each option check documentation.
  618. @param {String|DOMElement} settings.browse_button id of the DOM element or DOM element itself to use as file dialog trigger.
  619. @param {String} settings.url URL of the server-side upload handler.
  620. @param {Number|String} [settings.chunk_size=0] Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. `e.g. 204800 or "204800b" or "200kb"`. By default - disabled.
  621. @param {String} [settings.container] id of the DOM element to use as a container for uploader structures. Defaults to document.body.
  622. @param {String|DOMElement} [settings.drop_element] id of the DOM element or DOM element itself to use as a drop zone for Drag-n-Drop.
  623. @param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message.
  624. @param {Object} [settings.filters={}] Set of file type filters.
  625. @param {Array} [settings.filters.mime_types=[]] List of file types to accept, each one defined by title and list of extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR`
  626. @param {String|Number} [settings.filters.max_file_size=0] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`.
  627. @param {Boolean} [settings.filters.prevent_duplicates=false] Do not let duplicates into the queue. Dispatches `plupload.FILE_DUPLICATE_ERROR`.
  628. @param {String} [settings.flash_swf_url] URL of the Flash swf.
  629. @param {Object} [settings.headers] Custom headers to send with the upload. Hash of name/value pairs.
  630. @param {Number} [settings.max_retries=0] How many times to retry the chunk or file, before triggering Error event.
  631. @param {Boolean} [settings.multipart=true] Whether to send file and additional parameters as Multipart formated message.
  632. @param {Object} [settings.multipart_params] Hash of key/value pairs to send with every file upload.
  633. @param {Boolean} [settings.multi_selection=true] Enable ability to select multiple files at once in file dialog.
  634. @param {String|Object} [settings.required_features] Either comma-separated list or hash of required features that chosen runtime should absolutely possess.
  635. @param {Object} [settings.resize] Enable resizng of images on client-side. Applies to `image/jpeg` and `image/png` only. `e.g. {width : 200, height : 200, quality : 90, crop: true}`
  636. @param {Number} [settings.resize.width] If image is bigger, it will be resized.
  637. @param {Number} [settings.resize.height] If image is bigger, it will be resized.
  638. @param {Number} [settings.resize.quality=90] Compression quality for jpegs (1-100).
  639. @param {Boolean} [settings.resize.crop=false] Whether to crop images to exact dimensions. By default they will be resized proportionally.
  640. @param {String} [settings.runtimes="html5,flash,silverlight,html4"] Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails.
  641. @param {String} [settings.silverlight_xap_url] URL of the Silverlight xap.
  642. @param {Boolean} [settings.unique_names=false] If true will generate unique filenames for uploaded files.
  643. */
  644. plupload.Uploader = function(settings) {
  645. /**
  646. * Fires when the current RunTime has been initialized.
  647. *
  648. * @event Init
  649. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  650. */
  651. /**
  652. * Fires after the init event incase you need to perform actions there.
  653. *
  654. * @event PostInit
  655. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  656. */
  657. /**
  658. * Fires when the silverlight/flash or other shim needs to move.
  659. *
  660. * @event Refresh
  661. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  662. */
  663. /**
  664. * Fires when the overall state is being changed for the upload queue.
  665. *
  666. * @event StateChanged
  667. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  668. */
  669. /**
  670. * Fires when a file is to be uploaded by the runtime.
  671. *
  672. * @event UploadFile
  673. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  674. * @param {plupload.File} file File to be uploaded.
  675. */
  676. /**
  677. * Fires when just before a file is uploaded. This event enables you to override settings
  678. * on the uploader instance before the file is uploaded.
  679. *
  680. * @event BeforeUpload
  681. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  682. * @param {plupload.File} file File to be uploaded.
  683. */
  684. /**
  685. * Fires when the file queue is changed. In other words when files are added/removed to the files array of the uploader instance.
  686. *
  687. * @event QueueChanged
  688. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  689. */
  690. /**
  691. * Fires while a file is being uploaded. Use this event to update the current file upload progress.
  692. *
  693. * @event UploadProgress
  694. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  695. * @param {plupload.File} file File that is currently being uploaded.
  696. */
  697. /**
  698. * Fires while a file was removed from queue.
  699. *
  700. * @event FilesRemoved
  701. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  702. * @param {Array} files Array of files that got removed.
  703. */
  704. /**
  705. * Fires after files were filtered and added to the queue.
  706. *
  707. * @event FilesAdded
  708. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  709. * @param {Array} files Array of file objects that were added to queue by the user.
  710. */
  711. /**
  712. * Fires when a file is successfully uploaded.
  713. *
  714. * @event FileUploaded
  715. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  716. * @param {plupload.File} file File that was uploaded.
  717. * @param {Object} response Object with response properties.
  718. */
  719. /**
  720. * Fires when file chunk is uploaded.
  721. *
  722. * @event ChunkUploaded
  723. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  724. * @param {plupload.File} file File that the chunk was uploaded for.
  725. * @param {Object} response Object with response properties.
  726. */
  727. /**
  728. * Fires when all files in a queue are uploaded.
  729. *
  730. * @event UploadComplete
  731. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  732. * @param {Array} files Array of file objects that was added to queue/selected by the user.
  733. */
  734. /**
  735. * Fires when a error occurs.
  736. *
  737. * @event Error
  738. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  739. * @param {Object} error Contains code, message and sometimes file and other details.
  740. */
  741. /**
  742. * Fires when destroy method is called.
  743. *
  744. * @event Destroy
  745. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  746. */
  747. var files = [], events = {}, required_caps = {},
  748. startTime, total, disabled = false,
  749. fileInput, fileDrop, xhr;
  750. // Private methods
  751. function uploadNext() {
  752. var file, count = 0, i;
  753. if (this.state == plupload.STARTED) {
  754. // Find first QUEUED file
  755. for (i = 0; i < files.length; i++) {
  756. if (!file && files[i].status == plupload.QUEUED) {
  757. file = files[i];
  758. if (this.trigger("BeforeUpload", file)) {
  759. file.status = plupload.UPLOADING;
  760. this.trigger("UploadFile", file);
  761. }
  762. } else {
  763. count++;
  764. }
  765. }
  766. // All files are DONE or FAILED
  767. if (count == files.length) {
  768. if (this.state !== plupload.STOPPED) {
  769. this.state = plupload.STOPPED;
  770. this.trigger("StateChanged");
  771. }
  772. this.trigger("UploadComplete", files);
  773. }
  774. }
  775. }
  776. function calcFile(file) {
  777. file.percent = file.size > 0 ? Math.ceil(file.loaded / file.size * 100) : 100;
  778. calc();
  779. }
  780. function calc() {
  781. var i, file;
  782. // Reset stats
  783. total.reset();
  784. // Check status, size, loaded etc on all files
  785. for (i = 0; i < files.length; i++) {
  786. file = files[i];
  787. if (file.size !== undef) {
  788. // We calculate totals based on original file size
  789. total.size += file.origSize;
  790. // Since we cannot predict file size after resize, we do opposite and
  791. // interpolate loaded amount to match magnitude of total
  792. total.loaded += file.loaded * file.origSize / file.size;
  793. } else {
  794. total.size = undef;
  795. }
  796. if (file.status == plupload.DONE) {
  797. total.uploaded++;
  798. } else if (file.status == plupload.FAILED) {
  799. total.failed++;
  800. } else {
  801. total.queued++;
  802. }
  803. }
  804. // If we couldn't calculate a total file size then use the number of files to calc percent
  805. if (total.size === undef) {
  806. total.percent = files.length > 0 ? Math.ceil(total.uploaded / files.length * 100) : 0;
  807. } else {
  808. total.bytesPerSec = Math.ceil(total.loaded / ((+new Date() - startTime || 1) / 1000.0));
  809. total.percent = total.size > 0 ? Math.ceil(total.loaded / total.size * 100) : 0;
  810. }
  811. }
  812. function initControls() {
  813. var self = this, initialized = 0;
  814. // common settings
  815. var options = {
  816. accept: settings.filters.mime_types,
  817. runtime_order: settings.runtimes,
  818. required_caps: required_caps,
  819. swf_url: settings.flash_swf_url,
  820. xap_url: settings.silverlight_xap_url
  821. };
  822. // add runtime specific options if any
  823. plupload.each(settings.runtimes.split(/\s*,\s*/), function(runtime) {
  824. if (settings[runtime]) {
  825. options[runtime] = settings[runtime];
  826. }
  827. });
  828. o.inSeries([
  829. function(cb) {
  830. // Initialize file dialog trigger
  831. if (settings.browse_button) {
  832. fileInput = new o.FileInput(plupload.extend({}, options, {
  833. name: settings.file_data_name,
  834. multiple: settings.multi_selection,
  835. container: settings.container,
  836. browse_button: settings.browse_button
  837. }));
  838. fileInput.onready = function() {
  839. var info = o.Runtime.getInfo(this.ruid);
  840. // for backward compatibility
  841. o.extend(self.features, {
  842. chunks: info.can('slice_blob'),
  843. multipart: info.can('send_multipart'),
  844. multi_selection: info.can('select_multiple')
  845. });
  846. initialized++;
  847. cb();
  848. };
  849. fileInput.onchange = function() {
  850. self.addFile(this.files);
  851. };
  852. fileInput.bind('mouseenter mouseleave mousedown mouseup', function(e) {
  853. if (!disabled) {
  854. var bButton = o.get(settings.browse_button);
  855. if (bButton) {
  856. if (settings.browse_button_hover) {
  857. if ('mouseenter' === e.type) {
  858. o.addClass(bButton, settings.browse_button_hover);
  859. } else if ('mouseleave' === e.type) {
  860. o.removeClass(bButton, settings.browse_button_hover);
  861. }
  862. }
  863. if (settings.browse_button_active) {
  864. if ('mousedown' === e.type) {
  865. o.addClass(bButton, settings.browse_button_active);
  866. } else if ('mouseup' === e.type) {
  867. o.removeClass(bButton, settings.browse_button_active);
  868. }
  869. }
  870. bButton = null;
  871. }
  872. }
  873. });
  874. fileInput.bind('error runtimeerror', function() {
  875. fileInput = null;
  876. cb();
  877. });
  878. fileInput.init();
  879. } else {
  880. cb();
  881. }
  882. },
  883. function(cb) {
  884. // Initialize drag/drop interface if requested
  885. if (settings.drop_element) {
  886. fileDrop = new o.FileDrop(plupload.extend({}, options, {
  887. drop_zone: settings.drop_element
  888. }));
  889. fileDrop.onready = function() {
  890. var info = o.Runtime.getInfo(this.ruid);
  891. self.features.dragdrop = info.can('drag_and_drop');
  892. initialized++;
  893. cb();
  894. };
  895. fileDrop.ondrop = function() {
  896. self.addFile(this.files);
  897. };
  898. fileDrop.bind('error runtimeerror', function() {
  899. fileDrop = null;
  900. cb();
  901. });
  902. fileDrop.init();
  903. } else {
  904. cb();
  905. }
  906. }
  907. ],
  908. function() {
  909. if (typeof(settings.init) == "function") {
  910. settings.init(self);
  911. } else {
  912. plupload.each(settings.init, function(func, name) {
  913. self.bind(name, func);
  914. });
  915. }
  916. if (initialized) {
  917. self.trigger('PostInit');
  918. } else {
  919. self.trigger('Error', {
  920. code : plupload.INIT_ERROR,
  921. message : plupload.translate('Init error.')
  922. });
  923. }
  924. });
  925. }
  926. function runtimeCan(file, cap) {
  927. if (file.ruid) {
  928. var info = o.Runtime.getInfo(file.ruid);
  929. if (info) {
  930. return info.can(cap);
  931. }
  932. }
  933. return false;
  934. }
  935. function resizeImage(blob, params, cb) {
  936. var img = new o.Image();
  937. try {
  938. img.onload = function() {
  939. img.downsize(params.width, params.height, params.crop, params.preserve_headers);
  940. };
  941. img.onresize = function() {
  942. cb(this.getAsBlob(blob.type, params.quality));
  943. this.destroy();
  944. };
  945. img.onerror = function() {
  946. cb(blob);
  947. };
  948. img.load(blob);
  949. } catch(ex) {
  950. cb(blob);
  951. }
  952. }
  953. // Inital total state
  954. total = new plupload.QueueProgress();
  955. // Default settings
  956. settings = plupload.extend({
  957. runtimes: o.Runtime.order,
  958. max_retries: 0,
  959. multipart : true,
  960. multi_selection : true,
  961. file_data_name : 'file',
  962. flash_swf_url : 'js/Moxie.swf',
  963. silverlight_xap_url : 'js/Moxie.xap',
  964. send_chunk_number: true // whether to send chunks and chunk numbers, or total and offset bytes
  965. }, settings);
  966. // Resize defaults
  967. if (settings.resize) {
  968. settings.resize = plupload.extend({
  969. preserve_headers: true,
  970. crop: false
  971. }, settings.resize);
  972. }
  973. // Set file filters
  974. if (plupload.typeOf(settings.filters) === 'array') {
  975. settings.filters = {
  976. mime_types: settings.filters
  977. };
  978. }
  979. settings.filters = plupload.extend({
  980. mime_types: [],
  981. prevent_duplicates: !!settings.prevent_duplicates,
  982. max_file_size: settings.max_file_size
  983. }, settings.filters);
  984. // Convert settings
  985. settings.filters.max_file_size = plupload.parseSize(settings.filters.max_file_size) || 0;
  986. settings.chunk_size = plupload.parseSize(settings.chunk_size) || 0;
  987. // Normalize the list of required capabilities
  988. settings.required_features = required_caps = normalizeCaps(plupload.extend({}, settings));
  989. // Add public methods
  990. plupload.extend(this, {
  991. /**
  992. * Unique id for the Uploader instance.
  993. *
  994. * @property id
  995. * @type String
  996. */
  997. id : plupload.guid(),
  998. /**
  999. * Current state of the total uploading progress. This one can either be plupload.STARTED or plupload.STOPPED.
  1000. * These states are controlled by the stop/start methods. The default value is STOPPED.
  1001. *
  1002. * @property state
  1003. * @type Number
  1004. */
  1005. state : plupload.STOPPED,
  1006. /**
  1007. * Map of features that are available for the uploader runtime. Features will be filled
  1008. * before the init event is called, these features can then be used to alter the UI for the end user.
  1009. * Some of the current features that might be in this map is: dragdrop, chunks, jpgresize, pngresize.
  1010. *
  1011. * @property features
  1012. * @type Object
  1013. */
  1014. features : {},
  1015. /**
  1016. * Current runtime name.
  1017. *
  1018. * @property runtime
  1019. * @type String
  1020. */
  1021. runtime : o.Runtime.thatCan(required_caps, settings.runtimes), // predict runtime
  1022. /**
  1023. * Current upload queue, an array of File instances.
  1024. *
  1025. * @property files
  1026. * @type Array
  1027. * @see plupload.File
  1028. */
  1029. files : files,
  1030. /**
  1031. * Object with name/value settings.
  1032. *
  1033. * @property settings
  1034. * @type Object
  1035. */
  1036. settings : settings,
  1037. /**
  1038. * Total progess information. How many files has been uploaded, total percent etc.
  1039. *
  1040. * @property total
  1041. * @type plupload.QueueProgress
  1042. */
  1043. total : total,
  1044. /**
  1045. * Initializes the Uploader instance and adds internal event listeners.
  1046. *
  1047. * @method init
  1048. */
  1049. init : function() {
  1050. var self = this;
  1051. settings.browse_button = o.get(settings.browse_button);
  1052. // Check if drop zone requested
  1053. settings.drop_element = o.get(settings.drop_element);
  1054. if (typeof(settings.preinit) == "function") {
  1055. settings.preinit(self);
  1056. } else {
  1057. plupload.each(settings.preinit, function(func, name) {
  1058. self.bind(name, func);
  1059. });
  1060. }
  1061. // Check for required options
  1062. if (!settings.browse_button || !settings.url) {
  1063. this.trigger('Error', {
  1064. code : plupload.INIT_ERROR,
  1065. message : plupload.translate('Init error.')
  1066. });
  1067. return;
  1068. }
  1069. self.bind("FilesAdded", function(up, filteredFiles) {
  1070. // Add files to queue
  1071. [].push.apply(files, filteredFiles);
  1072. delay(function() {
  1073. self.trigger("QueueChanged");
  1074. self.refresh();
  1075. }, 1);
  1076. });
  1077. self.bind("CancelUpload", function() {
  1078. if (xhr) {
  1079. xhr.abort();
  1080. }
  1081. });
  1082. // Generate unique target filenames
  1083. if (settings.unique_names) {
  1084. self.bind("BeforeUpload", function(up, file) {
  1085. var matches = file.name.match(/\.([^.]+)$/), ext = "part";
  1086. if (matches) {
  1087. ext = matches[1];
  1088. }
  1089. file.target_name = file.id + '.' + ext;
  1090. });
  1091. }
  1092. self.bind("UploadFile", function(up, file) {
  1093. var url = up.settings.url, features = up.features, chunkSize = settings.chunk_size,
  1094. retries = settings.max_retries,
  1095. blob, offset = 0;
  1096. // make sure we start at a predictable offset
  1097. if (file.loaded) {
  1098. offset = file.loaded = chunkSize * Math.floor(file.loaded / chunkSize);
  1099. }
  1100. function handleError() {
  1101. if (retries-- > 0) {
  1102. delay(uploadNextChunk, 1);
  1103. } else {
  1104. file.loaded = offset; // reset all progress
  1105. up.trigger('Error', {
  1106. code : plupload.HTTP_ERROR,
  1107. message : plupload.translate('HTTP Error.'),
  1108. file : file,
  1109. response : xhr.responseText,
  1110. status : xhr.status,
  1111. responseHeaders: xhr.getAllResponseHeaders()
  1112. });
  1113. }
  1114. }
  1115. function uploadNextChunk() {
  1116. var chunkBlob, formData, args, curChunkSize;
  1117. // File upload finished
  1118. if (file.status == plupload.DONE || file.status == plupload.FAILED || up.state == plupload.STOPPED) {
  1119. return;
  1120. }
  1121. // Standard arguments
  1122. args = {name : file.target_name || file.name};
  1123. if (chunkSize && features.chunks && blob.size > chunkSize) { // blob will be of type string if it was loaded in memory
  1124. curChunkSize = Math.min(chunkSize, blob.size - offset);
  1125. chunkBlob = blob.slice(offset, offset + curChunkSize);
  1126. } else {
  1127. curChunkSize = blob.size;
  1128. chunkBlob = blob;
  1129. }
  1130. // If chunking is enabled add corresponding args, no matter if file is bigger than chunk or smaller
  1131. if (chunkSize && features.chunks) {
  1132. // Setup query string arguments
  1133. if (settings.send_chunk_number) {
  1134. args.chunk = Math.ceil(offset / chunkSize);
  1135. args.chunks = Math.ceil(blob.size / chunkSize);
  1136. } else { // keep support for experimental chunk format, just in case
  1137. args.offset = offset;
  1138. args.total = blob.size;
  1139. }
  1140. }
  1141. xhr = new o.XMLHttpRequest();
  1142. // Do we have upload progress support
  1143. if (xhr.upload) {
  1144. xhr.upload.onprogress = function(e) {
  1145. file.loaded = Math.min(file.size, offset + e.loaded);
  1146. up.trigger('UploadProgress', file);
  1147. };
  1148. }
  1149. xhr.onload = function() {
  1150. // check if upload made itself through
  1151. if (xhr.status >= 400) {
  1152. handleError();
  1153. return;
  1154. }
  1155. // Handle chunk response
  1156. if (curChunkSize < blob.size) {
  1157. chunkBlob.destroy();
  1158. offset += curChunkSize;
  1159. file.loaded = Math.min(offset, blob.size);
  1160. up.trigger('ChunkUploaded', file, {
  1161. offset : file.loaded,
  1162. total : blob.size,
  1163. response : xhr.responseText,
  1164. status : xhr.status,
  1165. responseHeaders: xhr.getAllResponseHeaders()
  1166. });
  1167. // stock Android browser doesn't fire upload progress events, but in chunking mode we can fake them
  1168. if (o.Env.browser === 'Android Browser') {
  1169. // doesn't harm in general, but is not required anywhere else
  1170. up.trigger('UploadProgress', file);
  1171. }
  1172. } else {
  1173. file.loaded = file.size;
  1174. }
  1175. chunkBlob = formData = null; // Free memory
  1176. // Check if file is uploaded
  1177. if (!offset || offset >= blob.size) {
  1178. // If file was modified, destory the copy
  1179. if (file.size != file.origSize) {
  1180. blob.destroy();
  1181. blob = null;
  1182. }
  1183. up.trigger('UploadProgress', file);
  1184. file.status = plupload.DONE;
  1185. up.trigger('FileUploaded', file, {
  1186. response : xhr.responseText,
  1187. status : xhr.status,
  1188. responseHeaders: xhr.getAllResponseHeaders()
  1189. });
  1190. } else {
  1191. // Still chunks left
  1192. delay(uploadNextChunk, 1); // run detached, otherwise event handlers interfere
  1193. }
  1194. };
  1195. xhr.onerror = function() {
  1196. handleError();
  1197. };
  1198. xhr.onloadend = function() {
  1199. this.destroy();
  1200. xhr = null;
  1201. };
  1202. // Build multipart request
  1203. if (up.settings.multipart && features.multipart) {
  1204. args.name = file.target_name || file.name;
  1205. xhr.open("post", url, true);
  1206. // Set custom headers
  1207. plupload.each(up.settings.headers, function(value, name) {
  1208. xhr.setRequestHeader(name, value);
  1209. });
  1210. formData = new o.FormData();
  1211. // Add multipart params
  1212. plupload.each(plupload.extend(args, up.settings.multipart_params), function(value, name) {
  1213. formData.append(name, value);
  1214. });
  1215. // Add file and send it
  1216. formData.append(up.settings.file_data_name, chunkBlob);
  1217. xhr.send(formData, {
  1218. runtime_order: up.settings.runtimes,
  1219. required_caps: required_caps,
  1220. swf_url: up.settings.flash_swf_url,
  1221. xap_url: up.settings.silverlight_xap_url
  1222. });
  1223. } else {
  1224. // if no multipart, send as binary stream
  1225. url = plupload.buildUrl(up.settings.url, plupload.extend(args, up.settings.multipart_params));
  1226. xhr.open("post", url, true);
  1227. xhr.setRequestHeader('Content-Type', 'application/octet-stream'); // Binary stream header
  1228. // Set custom headers
  1229. plupload.each(up.settings.headers, function(value, name) {
  1230. xhr.setRequestHeader(name, value);
  1231. });
  1232. xhr.send(chunkBlob, {
  1233. runtime_order: up.settings.runtimes,
  1234. required_caps: required_caps,
  1235. swf_url: up.settings.flash_swf_url,
  1236. xap_url: up.settings.silverlight_xap_url
  1237. });
  1238. }
  1239. }
  1240. blob = file.getSource();
  1241. // Start uploading chunks
  1242. if (!o.isEmptyObj(up.settings.resize) && runtimeCan(blob, 'send_binary_string') && !!~o.inArray(blob.type, ['image/jpeg', 'image/png'])) {
  1243. // Resize if required
  1244. resizeImage.call(this, blob, up.settings.resize, function(resizedBlob) {
  1245. blob = resizedBlob;
  1246. file.size = resizedBlob.size;
  1247. uploadNextChunk();
  1248. });
  1249. } else {
  1250. uploadNextChunk();
  1251. }
  1252. });
  1253. self.bind('UploadProgress', function(up, file) {
  1254. calcFile(file);
  1255. });
  1256. self.bind('StateChanged', function(up) {
  1257. if (up.state == plupload.STARTED) {
  1258. // Get start time to calculate bps
  1259. startTime = (+new Date());
  1260. } else if (up.state == plupload.STOPPED) {
  1261. // Reset currently uploading files
  1262. for (var i = up.files.length - 1; i >= 0; i--) {
  1263. if (up.files[i].status == plupload.UPLOADING) {
  1264. up.files[i].status = plupload.QUEUED;
  1265. calc();
  1266. }
  1267. }
  1268. }
  1269. });
  1270. self.bind('QueueChanged', calc);
  1271. self.bind("Error", function(up, err) {
  1272. // Set failed status if an error occured on a file
  1273. if (err.file) {
  1274. err.file.status = plupload.FAILED;
  1275. calcFile(err.file);
  1276. // Upload next file but detach it from the error event
  1277. // since other custom listeners might want to stop the queue
  1278. if (up.state == plupload.STARTED) {
  1279. delay(function() {
  1280. uploadNext.call(self);
  1281. }, 1);
  1282. }
  1283. }
  1284. });
  1285. self.bind("FileUploaded", function() {
  1286. calc();
  1287. // Upload next file but detach it from the error event
  1288. // since other custom listeners might want to stop the queue
  1289. delay(function() {
  1290. uploadNext.call(self);
  1291. }, 1);
  1292. });
  1293. // some dependent scripts hook onto Init to alter configuration options, raw UI, etc (like Queue Widget),
  1294. // therefore we got to fire this one, before we dive into the actual initializaion
  1295. self.trigger('Init', { runtime: this.runtime });
  1296. initControls.call(this);
  1297. },
  1298. /**
  1299. * Refreshes the upload instance by dispatching out a refresh event to all runtimes.
  1300. * This would for example reposition flash/silverlight shims on the page.
  1301. *
  1302. * @method refresh
  1303. */
  1304. refresh : function() {
  1305. if (fileInput) {
  1306. fileInput.trigger("Refresh");
  1307. }
  1308. this.trigger("Refresh");
  1309. },
  1310. /**
  1311. * Starts uploading the queued files.
  1312. *
  1313. * @method start
  1314. */
  1315. start : function() {
  1316. if (this.state != plupload.STARTED) {
  1317. this.state = plupload.STARTED;
  1318. this.trigger("StateChanged");
  1319. uploadNext.call(this);
  1320. }
  1321. },
  1322. /**
  1323. * Stops the upload of the queued files.
  1324. *
  1325. * @method stop
  1326. */
  1327. stop : function() {
  1328. if (this.state != plupload.STOPPED) {
  1329. this.state = plupload.STOPPED;
  1330. this.trigger("StateChanged");
  1331. this.trigger("CancelUpload");
  1332. }
  1333. },
  1334. /**
  1335. * Disables/enables browse button on request.
  1336. *
  1337. * @method disableBrowse
  1338. * @param {Boolean} disable Whether to disable or enable (default: true)
  1339. */
  1340. disableBrowse : function() {
  1341. disabled = arguments[0] !== undef ? arguments[0] : true;
  1342. if (fileInput) {
  1343. fileInput.disable(disabled);
  1344. }
  1345. this.trigger("DisableBrowse", disabled);
  1346. },
  1347. /**
  1348. * Returns the specified file object by id.
  1349. *
  1350. * @method getFile
  1351. * @param {String} id File id to look for.
  1352. * @return {plupload.File} File object or undefined if it wasn't found;
  1353. */
  1354. getFile : function(id) {
  1355. var i;
  1356. for (i = files.length - 1; i >= 0; i--) {
  1357. if (files[i].id === id) {
  1358. return files[i];
  1359. }
  1360. }
  1361. },
  1362. /**
  1363. * Adds file to the queue programmatically. Can be native file, instance of Plupload.File,
  1364. * instance of mOxie.File, input[type="file"] element, or array of these. Fires FilesAdded,
  1365. * if any files were added to the queue. Otherwise nothing happens.
  1366. *
  1367. * @method addFile
  1368. * @param {plupload.File|mOxie.File|File|Node|Array} file File or files to add to the queue.
  1369. * @param {String} [fileName] If specified, will be used as a name for the file
  1370. */
  1371. addFile : function(file, fileName) {
  1372. var self = this
  1373. , queue = []
  1374. , files = []
  1375. , ruid
  1376. ;
  1377. function getRUID() {
  1378. var ctrl = fileDrop || fileInput;
  1379. if (ctrl) {
  1380. return ctrl.getRuntime().uid;
  1381. }
  1382. return false;
  1383. }
  1384. function filterFile(file, cb) {
  1385. var queue = [];
  1386. o.each(self.settings.filters, function(rule, name) {
  1387. if (fileFilters[name]) {
  1388. queue.push(function(cb) {
  1389. fileFilters[name].call(self, rule, file, function(res) {
  1390. cb(!res);
  1391. });
  1392. });
  1393. }
  1394. });
  1395. o.inSeries(queue, cb);
  1396. }
  1397. /**
  1398. * @method resolveFile
  1399. * @private
  1400. * @param {o.File|o.Blob|plupload.File|File|Blob|input[type="file"]} file
  1401. */
  1402. function resolveFile(file) {
  1403. var type = o.typeOf(file);
  1404. // o.File
  1405. if (file instanceof o.File) {
  1406. if (!file.ruid && !file.isDetached()) {
  1407. if (!ruid) { // weird case
  1408. return false;
  1409. }
  1410. file.ruid = ruid;
  1411. file.connectRuntime(ruid);
  1412. }
  1413. resolveFile(new plupload.File(file));
  1414. }
  1415. // o.Blob
  1416. else if (file instanceof o.Blob) {
  1417. resolveFile(file.getSource());
  1418. file.destroy();
  1419. }
  1420. // plupload.File - final step for other branches
  1421. else if (file instanceof plupload.File) {
  1422. if (fileName) {
  1423. file.name = fileName;
  1424. }
  1425. queue.push(function(cb) {
  1426. // run through the internal and user-defined filters, if any
  1427. filterFile(file, function(err) {
  1428. if (!err) {
  1429. files.push(file);
  1430. }
  1431. cb();
  1432. });
  1433. });
  1434. }
  1435. // native File or blob
  1436. else if (o.inArray(type, ['file', 'blob']) !== -1) {
  1437. resolveFile(new o.File(null, file));
  1438. }
  1439. // input[type="file"]
  1440. else if (type === 'node' && o.typeOf(file.files) === 'filelist') {
  1441. // if we are dealing with input[type="file"]
  1442. o.each(file.files, resolveFile);
  1443. }
  1444. // mixed array of any supported types (see above)
  1445. else if (type === 'array') {
  1446. fileName = null; // should never happen, but unset anyway to avoid funny situations
  1447. o.each(file, resolveFile);
  1448. }
  1449. }
  1450. ruid = getRUID();
  1451. resolveFile(file);
  1452. if (queue.length) {
  1453. o.inSeries(queue, function() {
  1454. // if any files left after filtration, trigger FilesAdded
  1455. if (files.length) {
  1456. self.trigger("FilesAdded", files);
  1457. }
  1458. });
  1459. }
  1460. },
  1461. /**
  1462. * Removes a specific file.
  1463. *
  1464. * @method removeFile
  1465. * @param {plupload.File|String} file File to remove from queue.
  1466. */
  1467. removeFile : function(file) {
  1468. var id = typeof(file) === 'string' ? file : file.id;
  1469. for (var i = files.length - 1; i >= 0; i--) {
  1470. if (files[i].id === id) {
  1471. return this.splice(i, 1)[0];
  1472. }
  1473. }
  1474. },
  1475. /**
  1476. * Removes part of the queue and returns the files removed. This will also trigger the FilesRemoved and QueueChanged events.
  1477. *
  1478. * @method splice
  1479. * @param {Number} start (Optional) Start index to remove from.
  1480. * @param {Number} length (Optional) Lengh of items to remove.
  1481. * @return {Array} Array of files that was removed.
  1482. */
  1483. splice : function(start, length) {
  1484. // Splice and trigger events
  1485. var removed = files.splice(start === undef ? 0 : start, length === undef ? files.length : length);
  1486. this.trigger("FilesRemoved", removed);
  1487. this.trigger("QueueChanged");
  1488. // Dispose any resources allocated by those files
  1489. plupload.each(removed, function(file) {
  1490. file.destroy();
  1491. });
  1492. return removed;
  1493. },
  1494. /**
  1495. * Dispatches the specified event name and it's arguments to all listeners.
  1496. *
  1497. *
  1498. * @method trigger
  1499. * @param {String} name Event name to fire.
  1500. * @param {Object..} Multiple arguments to pass along to the listener functions.
  1501. */
  1502. trigger : function(name) {
  1503. var list = events[name.toLowerCase()], i, args;
  1504. // console.log(name, arguments);
  1505. if (list) {
  1506. // Replace name with sender in args
  1507. args = Array.prototype.slice.call(arguments);
  1508. args[0] = this;
  1509. // Dispatch event to all listeners
  1510. for (i = 0; i < list.length; i++) {
  1511. // Fire event, break chain if false is returned
  1512. if (list[i].func.apply(list[i].scope, args) === false) {
  1513. return false;
  1514. }
  1515. }
  1516. }
  1517. return true;
  1518. },
  1519. /**
  1520. * Check whether uploader has any listeners to the specified event.
  1521. *
  1522. * @method hasEventListener
  1523. * @param {String} name Event name to check for.
  1524. */
  1525. hasEventListener : function(name) {
  1526. return !!events[name.toLowerCase()];
  1527. },
  1528. /**
  1529. * Adds an event listener by name.
  1530. *
  1531. * @method bind
  1532. * @param {String} name Event name to listen for.
  1533. * @param {function} func Function to call ones the event gets fired.
  1534. * @param {Object} scope Optional scope to execute the specified function in.
  1535. */
  1536. bind : function(name, func, scope) {
  1537. var list;
  1538. name = name.toLowerCase();
  1539. list = events[name] || [];
  1540. list.push({func : func, scope : scope || this});
  1541. events[name] = list;
  1542. },
  1543. /**
  1544. * Removes the specified event listener.
  1545. *
  1546. * @method unbind
  1547. * @param {String} name Name of event to remove.
  1548. * @param {function} func Function to remove from listener.
  1549. */
  1550. unbind : function(name) {
  1551. name = name.toLowerCase();
  1552. var list = events[name], i, func = arguments[1];
  1553. if (list) {
  1554. if (func !== undef) {
  1555. for (i = list.length - 1; i >= 0; i--) {
  1556. if (list[i].func === func) {
  1557. list.splice(i, 1);
  1558. break;
  1559. }
  1560. }
  1561. } else {
  1562. list = [];
  1563. }
  1564. // delete event list if it has become empty
  1565. if (!list.length) {
  1566. delete events[name];
  1567. }
  1568. }
  1569. },
  1570. /**
  1571. * Removes all event listeners.
  1572. *
  1573. * @method unbindAll
  1574. */
  1575. unbindAll : function() {
  1576. var self = this;
  1577. plupload.each(events, function(list, name) {
  1578. self.unbind(name);
  1579. });
  1580. },
  1581. /**
  1582. * Destroys Plupload instance and cleans after itself.
  1583. *
  1584. * @method destroy
  1585. */
  1586. destroy : function() {
  1587. this.stop();
  1588. // Purge the queue
  1589. plupload.each(files, function(file) {
  1590. file.destroy();
  1591. });
  1592. files = [];
  1593. if (fileInput) {
  1594. fileInput.destroy();
  1595. fileInput = null;
  1596. }
  1597. if (fileDrop) {
  1598. fileDrop.destroy();
  1599. fileDrop = null;
  1600. }
  1601. required_caps = {};
  1602. startTime = total = disabled = xhr = null;
  1603. this.trigger('Destroy');
  1604. // Clean-up after uploader itself
  1605. this.unbindAll();
  1606. events = {};
  1607. }
  1608. });
  1609. };
  1610. /**
  1611. * Constructs a new file instance.
  1612. *
  1613. * @class File
  1614. * @constructor
  1615. *
  1616. * @param {Object} file Object containing file properties
  1617. * @param {String} file.name Name of the file.
  1618. * @param {Number} file.size File size.
  1619. */
  1620. plupload.File = (function() {
  1621. var filepool = {};
  1622. function PluploadFile(file) {
  1623. plupload.extend(this, {
  1624. /**
  1625. * File id this is a globally unique id for the specific file.
  1626. *
  1627. * @property id
  1628. * @type String
  1629. */
  1630. id: plupload.guid(),
  1631. /**
  1632. * File name for example "myfile.gif".
  1633. *
  1634. * @property name
  1635. * @type String
  1636. */
  1637. name: file.name || file.fileName,
  1638. /**
  1639. * File type, `e.g image/jpeg`
  1640. *
  1641. * @property type
  1642. * @type String
  1643. */
  1644. type: file.type || '',
  1645. /**
  1646. * File size in bytes (may change after client-side manupilation).
  1647. *
  1648. * @property size
  1649. * @type Number
  1650. */
  1651. size: file.size || file.fileSize,
  1652. /**
  1653. * Original file size in bytes.
  1654. *
  1655. * @property origSize
  1656. * @type Number
  1657. */
  1658. origSize: file.size || file.fileSize,
  1659. /**
  1660. * Number of bytes uploaded of the files total size.
  1661. *
  1662. * @property loaded
  1663. * @type Number
  1664. */
  1665. loaded: 0,
  1666. /**
  1667. * Number of percentage uploaded of the file.
  1668. *
  1669. * @property percent
  1670. * @type Number
  1671. */
  1672. percent: 0,
  1673. /**
  1674. * Status constant matching the plupload states QUEUED, UPLOADING, FAILED, DONE.
  1675. *
  1676. * @property status
  1677. * @type Number
  1678. * @see plupload
  1679. */
  1680. status: plupload.QUEUED,
  1681. /**
  1682. * Date of last modification.
  1683. *
  1684. * @property lastModifiedDate
  1685. * @type {String}
  1686. */
  1687. lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString(), // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
  1688. /**
  1689. * Returns native window.File object, when it's available.
  1690. *
  1691. * @method getNative
  1692. * @return {window.File} or null, if plupload.File is of different origin
  1693. */
  1694. getNative: function() {
  1695. var file = this.getSource().getSource();
  1696. return o.inArray(o.typeOf(file), ['blob', 'file']) !== -1 ? file : null;
  1697. },
  1698. /**
  1699. * Returns mOxie.File - unified wrapper object that can be used across runtimes.
  1700. *
  1701. * @method getSource
  1702. * @return {mOxie.File} or null
  1703. */
  1704. getSource: function() {
  1705. if (!filepool[this.id]) {
  1706. return null;
  1707. }
  1708. return filepool[this.id];
  1709. },
  1710. /**
  1711. * Destroys plupload.File object.
  1712. *
  1713. * @method destroy
  1714. */
  1715. destroy: function() {
  1716. var src = this.getSource();
  1717. if (src) {
  1718. src.destroy();
  1719. delete filepool[this.id];
  1720. }
  1721. }
  1722. });
  1723. filepool[this.id] = file;
  1724. }
  1725. return PluploadFile;
  1726. }());
  1727. /**
  1728. * Constructs a queue progress.
  1729. *
  1730. * @class QueueProgress
  1731. * @constructor
  1732. */
  1733. plupload.QueueProgress = function() {
  1734. var self = this; // Setup alias for self to reduce code size when it's compressed
  1735. /**
  1736. * Total queue file size.
  1737. *
  1738. * @property size
  1739. * @type Number
  1740. */
  1741. self.size = 0;
  1742. /**
  1743. * Total bytes uploaded.
  1744. *
  1745. * @property loaded
  1746. * @type Number
  1747. */
  1748. self.loaded = 0;
  1749. /**
  1750. * Number of files uploaded.
  1751. *
  1752. * @property uploaded
  1753. * @type Number
  1754. */
  1755. self.uploaded = 0;
  1756. /**
  1757. * Number of files failed to upload.
  1758. *
  1759. * @property failed
  1760. * @type Number
  1761. */
  1762. self.failed = 0;
  1763. /**
  1764. * Number of files yet to be uploaded.
  1765. *
  1766. * @property queued
  1767. * @type Number
  1768. */
  1769. self.queued = 0;
  1770. /**
  1771. * Total percent of the uploaded bytes.
  1772. *
  1773. * @property percent
  1774. * @type Number
  1775. */
  1776. self.percent = 0;
  1777. /**
  1778. * Bytes uploaded per second.
  1779. *
  1780. * @property bytesPerSec
  1781. * @type Number
  1782. */
  1783. self.bytesPerSec = 0;
  1784. /**
  1785. * Resets the progress to it's initial values.
  1786. *
  1787. * @method reset
  1788. */
  1789. self.reset = function() {
  1790. self.size = self.loaded = self.uploaded = self.failed = self.queued = self.percent = self.bytesPerSec = 0;
  1791. };
  1792. };
  1793. window.plupload = plupload;
  1794. }(window, mOxie));