file_uploader.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. /**
  2. * DevExtreme (ui/file_uploader.js)
  3. * Version: 19.1.16
  4. * Build date: Tue Oct 18 2022
  5. *
  6. * Copyright (c) 2012 - 2022 Developer Express Inc. ALL RIGHTS RESERVED
  7. * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
  8. */
  9. "use strict";
  10. var $ = require("../core/renderer");
  11. var Class = require("../core/class");
  12. var Guid = require("../core/guid");
  13. var window = require("../core/utils/window").getWindow();
  14. var eventsEngine = require("../events/core/events_engine");
  15. var registerComponent = require("../core/component_registrator");
  16. var Callbacks = require("../core/utils/callbacks");
  17. var isDefined = require("../core/utils/type").isDefined;
  18. var each = require("../core/utils/iterator").each;
  19. var extend = require("../core/utils/extend").extend;
  20. var inArray = require("../core/utils/array").inArray;
  21. var ajax = require("../core/utils/ajax");
  22. var Editor = require("./editor/editor");
  23. var Button = require("./button");
  24. var ProgressBar = require("./progress_bar");
  25. var browser = require("../core/utils/browser");
  26. var devices = require("../core/devices");
  27. var eventUtils = require("../events/utils");
  28. var clickEvent = require("../events/click");
  29. var messageLocalization = require("../localization/message");
  30. var themes = require("./themes");
  31. var FILEUPLOADER_CLASS = "dx-fileuploader";
  32. var FILEUPLOADER_EMPTY_CLASS = "dx-fileuploader-empty";
  33. var FILEUPLOADER_SHOW_FILE_LIST_CLASS = "dx-fileuploader-show-file-list";
  34. var FILEUPLOADER_DRAGOVER_CLASS = "dx-fileuploader-dragover";
  35. var FILEUPLOADER_WRAPPER_CLASS = "dx-fileuploader-wrapper";
  36. var FILEUPLOADER_CONTAINER_CLASS = "dx-fileuploader-container";
  37. var FILEUPLOADER_CONTENT_CLASS = "dx-fileuploader-content";
  38. var FILEUPLOADER_INPUT_WRAPPER_CLASS = "dx-fileuploader-input-wrapper";
  39. var FILEUPLOADER_INPUT_CONTAINER_CLASS = "dx-fileuploader-input-container";
  40. var FILEUPLOADER_INPUT_LABEL_CLASS = "dx-fileuploader-input-label";
  41. var FILEUPLOADER_INPUT_CLASS = "dx-fileuploader-input";
  42. var FILEUPLOADER_FILES_CONTAINER_CLASS = "dx-fileuploader-files-container";
  43. var FILEUPLOADER_FILE_CONTAINER_CLASS = "dx-fileuploader-file-container";
  44. var FILEUPLOADER_FILE_INFO_CLASS = "dx-fileuploader-file-info";
  45. var FILEUPLOADER_FILE_STATUS_MESSAGE_CLASS = "dx-fileuploader-file-status-message";
  46. var FILEUPLOADER_FILE_CLASS = "dx-fileuploader-file";
  47. var FILEUPLOADER_FILE_NAME_CLASS = "dx-fileuploader-file-name";
  48. var FILEUPLOADER_FILE_SIZE_CLASS = "dx-fileuploader-file-size";
  49. var FILEUPLOADER_BUTTON_CLASS = "dx-fileuploader-button";
  50. var FILEUPLOADER_BUTTON_CONTAINER_CLASS = "dx-fileuploader-button-container";
  51. var FILEUPLOADER_CANCEL_BUTTON_CLASS = "dx-fileuploader-cancel-button";
  52. var FILEUPLOADER_UPLOAD_BUTTON_CLASS = "dx-fileuploader-upload-button";
  53. var FILEUPLOADER_INVALID_CLASS = "dx-fileuploader-invalid";
  54. var FILEUPLOADER_AFTER_LOAD_DELAY = 400;
  55. var FILEUPLOADER_CHUNK_META_DATA_NAME = "chunkMetadata";
  56. var renderFileUploaderInput = function() {
  57. return $("<input>").attr("type", "file")
  58. };
  59. var isFormDataSupported = function() {
  60. return !!window.FormData
  61. };
  62. var FileUploader = Editor.inherit({
  63. _uploadStrategy: null,
  64. _supportedKeys: function() {
  65. var click = function(e) {
  66. e.preventDefault();
  67. var $selectButton = this._selectButton.$element();
  68. eventsEngine.trigger($selectButton, clickEvent.name)
  69. };
  70. return extend(this.callBase(), {
  71. space: click,
  72. enter: click
  73. })
  74. },
  75. _setOptionsByReference: function() {
  76. this.callBase();
  77. extend(this._optionsByReference, {
  78. value: true
  79. })
  80. },
  81. _getDefaultOptions: function() {
  82. return extend(this.callBase(), {
  83. chunkSize: 0,
  84. value: [],
  85. selectButtonText: messageLocalization.format("dxFileUploader-selectFile"),
  86. uploadButtonText: messageLocalization.format("dxFileUploader-upload"),
  87. labelText: messageLocalization.format("dxFileUploader-dropFile"),
  88. name: "files[]",
  89. multiple: false,
  90. accept: "",
  91. uploadUrl: "/",
  92. allowCanceling: true,
  93. showFileList: true,
  94. progress: 0,
  95. readyToUploadMessage: messageLocalization.format("dxFileUploader-readyToUpload"),
  96. uploadedMessage: messageLocalization.format("dxFileUploader-uploaded"),
  97. uploadFailedMessage: messageLocalization.format("dxFileUploader-uploadFailedMessage"),
  98. uploadMode: "instantly",
  99. uploadMethod: "POST",
  100. uploadHeaders: {},
  101. onUploadStarted: null,
  102. onUploaded: null,
  103. onProgress: null,
  104. onUploadError: null,
  105. onUploadAborted: null,
  106. allowedFileExtensions: [],
  107. maxFileSize: 0,
  108. minFileSize: 0,
  109. invalidFileExtensionMessage: messageLocalization.format("dxFileUploader-invalidFileExtension"),
  110. invalidMaxFileSizeMessage: messageLocalization.format("dxFileUploader-invalidMaxFileSize"),
  111. invalidMinFileSizeMessage: messageLocalization.format("dxFileUploader-invalidMinFileSize"),
  112. extendSelection: true,
  113. validationMessageMode: "always",
  114. validationMessageOffset: {
  115. h: 0,
  116. v: 0
  117. },
  118. useNativeInputClick: false,
  119. useDragOver: true,
  120. nativeDropSupported: true,
  121. _uploadButtonType: "normal"
  122. })
  123. },
  124. _defaultOptionsRules: function() {
  125. return this.callBase().concat([{
  126. device: function() {
  127. return "desktop" === devices.real().deviceType && !devices.isSimulator()
  128. },
  129. options: {
  130. focusStateEnabled: true
  131. }
  132. }, {
  133. device: [{
  134. platform: "android"
  135. }, {
  136. platform: "win"
  137. }],
  138. options: {
  139. validationMessageOffset: {
  140. v: 0
  141. }
  142. }
  143. }, {
  144. device: function() {
  145. return "generic" !== devices.real().platform
  146. },
  147. options: {
  148. useDragOver: false
  149. }
  150. }, {
  151. device: function() {
  152. return !isFormDataSupported()
  153. },
  154. options: {
  155. uploadMode: "useForm"
  156. }
  157. }, {
  158. device: function() {
  159. return browser.msie || "generic" !== devices.real().platform
  160. },
  161. options: {
  162. nativeDropSupported: false
  163. }
  164. }, {
  165. device: function() {
  166. return themes.isMaterial()
  167. },
  168. options: {
  169. _uploadButtonType: "default"
  170. }
  171. }])
  172. },
  173. _init: function() {
  174. this.callBase.apply(this, arguments);
  175. this._initFileInput();
  176. this._initLabel();
  177. this._createFiles();
  178. this._createUploadStartedAction();
  179. this._createUploadedAction();
  180. this._createProgressAction();
  181. this._createUploadErrorAction();
  182. this._createUploadAbortedAction();
  183. this._setUploadStrategy()
  184. },
  185. _setUploadStrategy: function() {
  186. this._uploadStrategy = this.option("chunkSize") > 0 ? new ChunksFileUploadStrategy(this) : new WholeFileUploadStrategy(this)
  187. },
  188. _initFileInput: function() {
  189. this._isCustomClickEvent = false;
  190. if (!this._$fileInput) {
  191. this._$fileInput = renderFileUploaderInput();
  192. eventsEngine.on(this._$fileInput, "change", this._inputChangeHandler.bind(this));
  193. eventsEngine.on(this._$fileInput, "click", function(e) {
  194. e.stopPropagation();
  195. return this.option("useNativeInputClick") || this._isCustomClickEvent
  196. }.bind(this))
  197. }
  198. this._$fileInput.prop({
  199. multiple: this.option("multiple"),
  200. accept: this.option("accept"),
  201. tabIndex: -1
  202. })
  203. },
  204. _inputChangeHandler: function() {
  205. if (this._doPreventInputChange) {
  206. return
  207. }
  208. var fileName = this._$fileInput.val().replace(/^.*\\/, "");
  209. var files = this._$fileInput.prop("files");
  210. if (files && !files.length) {
  211. return
  212. }
  213. var value = files ? this._getFiles(files) : [{
  214. name: fileName
  215. }];
  216. this._changeValue(value);
  217. if ("instantly" === this.option("uploadMode")) {
  218. this._uploadFiles()
  219. }
  220. },
  221. _shouldFileListBeExtended: function() {
  222. return "useForm" !== this.option("uploadMode") && this.option("extendSelection") && this.option("multiple")
  223. },
  224. _removeDuplicates: function(files, value) {
  225. var result = [];
  226. for (var i = 0; i < value.length; i++) {
  227. if (!this._isFileInArray(files, value[i])) {
  228. result.push(value[i])
  229. }
  230. }
  231. return result
  232. },
  233. _isFileInArray: function(files, file) {
  234. for (var i = 0; i < files.length; i++) {
  235. var item = files[i];
  236. if (item.size === file.size && item.name === file.name) {
  237. return true
  238. }
  239. }
  240. return false
  241. },
  242. _changeValue: function(value) {
  243. var files = this._shouldFileListBeExtended() ? this.option("value").slice() : [];
  244. if ("instantly" !== this.option("uploadMode")) {
  245. value = this._removeDuplicates(files, value)
  246. }
  247. this.option("value", files.concat(value))
  248. },
  249. _getFiles: function(fileList) {
  250. var values = [];
  251. each(fileList, function(_, value) {
  252. values.push(value)
  253. });
  254. return values
  255. },
  256. _initLabel: function() {
  257. if (!this._$inputLabel) {
  258. this._$inputLabel = $("<div>")
  259. }
  260. this._$inputLabel.text(this.option("labelText"))
  261. },
  262. _focusTarget: function() {
  263. return this.$element().find("." + FILEUPLOADER_BUTTON_CLASS)
  264. },
  265. _getSubmitElement: function() {
  266. return this._$fileInput
  267. },
  268. _initMarkup: function() {
  269. this.callBase();
  270. this.$element().addClass(FILEUPLOADER_CLASS);
  271. this._renderWrapper();
  272. this._renderInputWrapper();
  273. this._renderSelectButton();
  274. this._renderInputContainer();
  275. this._renderUploadButton();
  276. this._preventRecreatingFiles = true
  277. },
  278. _render: function() {
  279. this._preventRecreatingFiles = false;
  280. this._renderDragEvents();
  281. this._renderFiles();
  282. this.callBase()
  283. },
  284. _createFileProgressBar: function(file) {
  285. file.progressBar = this._createProgressBar(file.value.size);
  286. file.progressBar.$element().appendTo(file.$file);
  287. this._initStatusMessage(file);
  288. this._initCancelButton(file)
  289. },
  290. _setStatusMessage: function(file, key) {
  291. setTimeout(function() {
  292. if (this.option("showFileList")) {
  293. if (file.$statusMessage) {
  294. file.$statusMessage.text(this.option(key));
  295. file.$statusMessage.css("display", "");
  296. file.progressBar.$element().remove()
  297. }
  298. }
  299. }.bind(this), FILEUPLOADER_AFTER_LOAD_DELAY)
  300. },
  301. _createFiles: function() {
  302. var value = this.option("value");
  303. if (!this._files || 0 === value.length || !this._shouldFileListBeExtended()) {
  304. this._preventFilesUploading(this._files);
  305. this._files = []
  306. }
  307. each(value.slice(this._files.length), function(_, value) {
  308. var file = this._createFile(value);
  309. this._validateFile(file);
  310. this._files.push(file)
  311. }.bind(this))
  312. },
  313. _preventFilesUploading: function(files) {
  314. each(files, function(_, file) {
  315. file.request && file.request.abort()
  316. }.bind(this))
  317. },
  318. _validateFile: function(file) {
  319. file.isValidFileExtension = this._validateFileExtension(file);
  320. file.isValidMinSize = this._validateMinFileSize(file);
  321. file.isValidMaxSize = this._validateMaxFileSize(file)
  322. },
  323. _validateFileExtension: function(file) {
  324. var allowedExtensions = this.option("allowedFileExtensions");
  325. var fileExtension = file.value.name.substring(file.value.name.lastIndexOf(".")).toLowerCase();
  326. if (0 === allowedExtensions.length) {
  327. return true
  328. }
  329. for (var i = 0; i < allowedExtensions.length; i++) {
  330. if (fileExtension === allowedExtensions[i].toLowerCase()) {
  331. return true
  332. }
  333. }
  334. return false
  335. },
  336. _validateMaxFileSize: function(file) {
  337. var fileSize = file.value.size;
  338. var maxFileSize = this.option("maxFileSize");
  339. return maxFileSize > 0 ? fileSize <= maxFileSize : true
  340. },
  341. _validateMinFileSize: function(file) {
  342. var fileSize = file.value.size;
  343. var minFileSize = this.option("minFileSize");
  344. return minFileSize > 0 ? fileSize >= minFileSize : true
  345. },
  346. _createUploadStartedAction: function() {
  347. this._uploadStartedAction = this._createActionByOption("onUploadStarted")
  348. },
  349. _createUploadedAction: function() {
  350. this._uploadedAction = this._createActionByOption("onUploaded")
  351. },
  352. _createProgressAction: function() {
  353. this._progressAction = this._createActionByOption("onProgress")
  354. },
  355. _createUploadAbortedAction: function() {
  356. this._uploadAbortedAction = this._createActionByOption("onUploadAborted")
  357. },
  358. _createUploadErrorAction: function() {
  359. this._uploadErrorAction = this._createActionByOption("onUploadError")
  360. },
  361. _createFile: function(value) {
  362. return {
  363. value: value,
  364. loadedSize: 0,
  365. onProgress: Callbacks(),
  366. onAbort: Callbacks(),
  367. onLoad: Callbacks(),
  368. onError: Callbacks(),
  369. onLoadStart: Callbacks(),
  370. isValidFileExtension: true,
  371. isValidMaxSize: true,
  372. isValidMinSize: true,
  373. isValid: function() {
  374. return this.isValidFileExtension && this.isValidMaxSize && this.isValidMinSize
  375. }
  376. }
  377. },
  378. _renderFiles: function() {
  379. var value = this.option("value");
  380. if (!this._$filesContainer) {
  381. this._$filesContainer = $("<div>").addClass(FILEUPLOADER_FILES_CONTAINER_CLASS).appendTo(this._$content)
  382. } else {
  383. if (!this._shouldFileListBeExtended() || 0 === value.length) {
  384. this._$filesContainer.empty()
  385. }
  386. }
  387. var showFileList = this.option("showFileList");
  388. if (showFileList) {
  389. var that = this;
  390. each(this._files, function(_, file) {
  391. if (!file.$file) {
  392. that._renderFile(file)
  393. }
  394. })
  395. }
  396. this.$element().toggleClass(FILEUPLOADER_SHOW_FILE_LIST_CLASS, showFileList);
  397. this._toggleFileUploaderEmptyClassName();
  398. this._updateFileNameMaxWidth();
  399. this._$validationMessage && this._$validationMessage.dxOverlay("instance").repaint()
  400. },
  401. _renderFile: function(file) {
  402. var value = file.value;
  403. var $fileContainer = $("<div>").addClass(FILEUPLOADER_FILE_CONTAINER_CLASS).appendTo(this._$filesContainer);
  404. this._renderFileButtons(file, $fileContainer);
  405. file.$file = $("<div>").addClass(FILEUPLOADER_FILE_CLASS).appendTo($fileContainer);
  406. var $fileInfo = $("<div>").addClass(FILEUPLOADER_FILE_INFO_CLASS).appendTo(file.$file);
  407. file.$statusMessage = $("<div>").addClass(FILEUPLOADER_FILE_STATUS_MESSAGE_CLASS).appendTo(file.$file);
  408. $("<div>").addClass(FILEUPLOADER_FILE_NAME_CLASS).text(value.name).appendTo($fileInfo);
  409. if (isDefined(value.size)) {
  410. $("<div>").addClass(FILEUPLOADER_FILE_SIZE_CLASS).text(this._getFileSize(value.size)).appendTo($fileInfo)
  411. }
  412. if (file.isValid()) {
  413. file.$statusMessage.text(this.option("readyToUploadMessage"))
  414. } else {
  415. if (!file.isValidFileExtension) {
  416. file.$statusMessage.append(this._createValidationElement("invalidFileExtensionMessage"))
  417. }
  418. if (!file.isValidMaxSize) {
  419. file.$statusMessage.append(this._createValidationElement("invalidMaxFileSizeMessage"))
  420. }
  421. if (!file.isValidMinSize) {
  422. file.$statusMessage.append(this._createValidationElement("invalidMinFileSizeMessage"))
  423. }
  424. $fileContainer.addClass(FILEUPLOADER_INVALID_CLASS)
  425. }
  426. },
  427. _createValidationElement: function(key) {
  428. return $("<span>").text(this.option(key))
  429. },
  430. _updateFileNameMaxWidth: function() {
  431. var cancelButtonsCount = this.option("allowCanceling") && "useForm" !== this.option("uploadMode") ? 1 : 0;
  432. var uploadButtonsCount = "useButtons" === this.option("uploadMode") ? 1 : 0;
  433. var filesContainerWidth = this._$filesContainer.find("." + FILEUPLOADER_FILE_CONTAINER_CLASS).first().width() || this._$filesContainer.width();
  434. var $buttonContainer = this._$filesContainer.find("." + FILEUPLOADER_BUTTON_CONTAINER_CLASS).eq(0);
  435. var buttonsWidth = $buttonContainer.width() * (cancelButtonsCount + uploadButtonsCount);
  436. var $fileSize = this._$filesContainer.find("." + FILEUPLOADER_FILE_SIZE_CLASS).eq(0);
  437. var prevFileSize = $fileSize.text();
  438. $fileSize.text("1000 Mb");
  439. var fileSizeWidth = $fileSize.width();
  440. $fileSize.text(prevFileSize);
  441. this._$filesContainer.find("." + FILEUPLOADER_FILE_NAME_CLASS).css("maxWidth", filesContainerWidth - buttonsWidth - fileSizeWidth)
  442. },
  443. _renderFileButtons: function(file, $container) {
  444. var $cancelButton = this._getCancelButton(file);
  445. $cancelButton && $container.append($cancelButton);
  446. var $uploadButton = this._getUploadButton(file);
  447. $uploadButton && $container.append($uploadButton)
  448. },
  449. _getCancelButton: function(file) {
  450. if ("useForm" === this.option("uploadMode")) {
  451. return null
  452. }
  453. file.cancelButton = this._createComponent($("<div>").addClass(FILEUPLOADER_BUTTON_CLASS + " " + FILEUPLOADER_CANCEL_BUTTON_CLASS), Button, {
  454. onClick: function() {
  455. this._removeFile(file)
  456. }.bind(this),
  457. icon: "close",
  458. visible: this.option("allowCanceling"),
  459. integrationOptions: {}
  460. });
  461. return $("<div>").addClass(FILEUPLOADER_BUTTON_CONTAINER_CLASS).append(file.cancelButton.$element())
  462. },
  463. _getUploadButton: function(file) {
  464. if (!file.isValid() || "useButtons" !== this.option("uploadMode")) {
  465. return null
  466. }
  467. file.uploadButton = this._createComponent($("<div>").addClass(FILEUPLOADER_BUTTON_CLASS + " " + FILEUPLOADER_UPLOAD_BUTTON_CLASS), Button, {
  468. onClick: function() {
  469. this._uploadFile(file)
  470. }.bind(this),
  471. icon: "upload"
  472. });
  473. file.onLoadStart.add(function() {
  474. file.uploadButton.$element().remove()
  475. }.bind(this));
  476. return $("<div>").addClass(FILEUPLOADER_BUTTON_CONTAINER_CLASS).append(file.uploadButton.$element())
  477. },
  478. _removeFile: function(file) {
  479. file.$file.parent().remove();
  480. this._files.splice(inArray(file, this._files), 1);
  481. var value = this.option("value").slice();
  482. value.splice(inArray(file.value, value), 1);
  483. this._preventRecreatingFiles = true;
  484. this.option("value", value);
  485. this._preventRecreatingFiles = false;
  486. this._toggleFileUploaderEmptyClassName();
  487. this._doPreventInputChange = true;
  488. this._$fileInput.val("");
  489. this._doPreventInputChange = false
  490. },
  491. _toggleFileUploaderEmptyClassName: function() {
  492. this.$element().toggleClass(FILEUPLOADER_EMPTY_CLASS, !this._files.length || this._hasInvalidFile(this._files))
  493. },
  494. _hasInvalidFile: function(files) {
  495. for (var i = 0; i < files.length; i++) {
  496. if (!files[i].isValid()) {
  497. return true
  498. }
  499. }
  500. return false
  501. },
  502. _getFileSize: function(size) {
  503. var i = 0;
  504. var labels = [messageLocalization.format("dxFileUploader-bytes"), messageLocalization.format("dxFileUploader-kb"), messageLocalization.format("dxFileUploader-Mb"), messageLocalization.format("dxFileUploader-Gb")];
  505. var count = labels.length - 1;
  506. while (i < count && size >= 1024) {
  507. size /= 1024;
  508. i++
  509. }
  510. return Math.round(size) + " " + labels[i]
  511. },
  512. _renderSelectButton: function() {
  513. var $button = $("<div>").addClass(FILEUPLOADER_BUTTON_CLASS).appendTo(this._$inputWrapper);
  514. this._selectButton = this._createComponent($button, Button, {
  515. text: this.option("selectButtonText"),
  516. focusStateEnabled: false,
  517. integrationOptions: {}
  518. });
  519. if ("desktop" === devices.real().deviceType) {
  520. this._selectButton.option("onClick", this._selectButtonClickHandler.bind(this))
  521. } else {
  522. eventsEngine.off($button, "click");
  523. eventsEngine.on($button, "click", this._selectButtonClickHandler.bind(this))
  524. }
  525. },
  526. _selectButtonClickHandler: function() {
  527. var that = this;
  528. if (that.option("useNativeInputClick")) {
  529. return
  530. }
  531. if (that.option("disabled")) {
  532. return false
  533. }
  534. that._isCustomClickEvent = true;
  535. eventsEngine.trigger(that._$fileInput, "click");
  536. that._isCustomClickEvent = false
  537. },
  538. _renderUploadButton: function() {
  539. if ("useButtons" !== this.option("uploadMode")) {
  540. return
  541. }
  542. var $uploadButton = $("<div>").addClass(FILEUPLOADER_BUTTON_CLASS).addClass(FILEUPLOADER_UPLOAD_BUTTON_CLASS).appendTo(this._$content);
  543. this._uploadButton = this._createComponent($uploadButton, Button, {
  544. text: this.option("uploadButtonText"),
  545. onClick: this._uploadButtonClickHandler.bind(this),
  546. type: this.option("_uploadButtonType"),
  547. integrationOptions: {}
  548. })
  549. },
  550. _uploadButtonClickHandler: function() {
  551. this._uploadFiles()
  552. },
  553. _shouldDragOverBeRendered: function() {
  554. return "useForm" !== this.option("uploadMode") || this.option("nativeDropSupported")
  555. },
  556. _renderInputContainer: function() {
  557. this._$inputContainer = $("<div>").addClass(FILEUPLOADER_INPUT_CONTAINER_CLASS).appendTo(this._$inputWrapper);
  558. if (!this._shouldDragOverBeRendered()) {
  559. this._$inputContainer.css("display", "none")
  560. }
  561. this._$fileInput.addClass(FILEUPLOADER_INPUT_CLASS);
  562. this._renderInput();
  563. this._$inputLabel.addClass(FILEUPLOADER_INPUT_LABEL_CLASS).appendTo(this._$inputContainer)
  564. },
  565. _renderInput: function() {
  566. if (this.option("useNativeInputClick")) {
  567. this._selectButton.option("template", this._selectButtonInputTemplate.bind(this))
  568. } else {
  569. this._$fileInput.appendTo(this._$inputContainer);
  570. this._selectButton.option("template", "content")
  571. }
  572. },
  573. _selectButtonInputTemplate: function(data, content) {
  574. var $content = $(content);
  575. var $text = $("<span>").addClass("dx-button-text").text(data.text);
  576. $content.append($text).append(this._$fileInput);
  577. return $content
  578. },
  579. _renderInputWrapper: function() {
  580. this._$inputWrapper = $("<div>").addClass(FILEUPLOADER_INPUT_WRAPPER_CLASS).appendTo(this._$content)
  581. },
  582. _renderDragEvents: function() {
  583. eventsEngine.off(this._$inputWrapper, "." + this.NAME);
  584. if (!this._shouldDragOverBeRendered()) {
  585. return
  586. }
  587. this._dragEventsTargets = [];
  588. eventsEngine.on(this._$inputWrapper, eventUtils.addNamespace("dragenter", this.NAME), this._dragEnterHandler.bind(this));
  589. eventsEngine.on(this._$inputWrapper, eventUtils.addNamespace("dragover", this.NAME), this._dragOverHandler.bind(this));
  590. eventsEngine.on(this._$inputWrapper, eventUtils.addNamespace("dragleave", this.NAME), this._dragLeaveHandler.bind(this));
  591. eventsEngine.on(this._$inputWrapper, eventUtils.addNamespace("drop", this.NAME), this._dropHandler.bind(this))
  592. },
  593. _useInputForDrop: function() {
  594. return this.option("nativeDropSupported") && "useForm" === this.option("uploadMode")
  595. },
  596. _dragEnterHandler: function(e) {
  597. if (this.option("disabled")) {
  598. return false
  599. }
  600. if (!this._useInputForDrop()) {
  601. e.preventDefault()
  602. }
  603. this._updateEventTargets(e);
  604. this.$element().addClass(FILEUPLOADER_DRAGOVER_CLASS)
  605. },
  606. _dragOverHandler: function(e) {
  607. if (!this._useInputForDrop()) {
  608. e.preventDefault()
  609. }
  610. },
  611. _dragLeaveHandler: function(e) {
  612. if (!this._useInputForDrop()) {
  613. e.preventDefault()
  614. }
  615. this._updateEventTargets(e);
  616. if (!this._dragEventsTargets.length) {
  617. this.$element().removeClass(FILEUPLOADER_DRAGOVER_CLASS)
  618. }
  619. },
  620. _updateEventTargets: function(e) {
  621. var targetIndex = this._dragEventsTargets.indexOf(e.target);
  622. var isTargetExists = targetIndex !== -1;
  623. if ("dragenter" === e.type) {
  624. !isTargetExists && this._dragEventsTargets.push(e.target)
  625. } else {
  626. isTargetExists && this._dragEventsTargets.splice(targetIndex, 1)
  627. }
  628. },
  629. _dropHandler: function(e) {
  630. this._dragEventsTargets = [];
  631. this.$element().removeClass(FILEUPLOADER_DRAGOVER_CLASS);
  632. if (this._useInputForDrop()) {
  633. return
  634. }
  635. e.preventDefault();
  636. var fileList = e.originalEvent.dataTransfer.files;
  637. var files = this._getFiles(fileList);
  638. if (!this.option("multiple") && files.length > 1) {
  639. return
  640. }
  641. this._changeValue(this._filterFiles(files));
  642. if ("instantly" === this.option("uploadMode")) {
  643. this._uploadFiles()
  644. }
  645. },
  646. _filterFiles: function(files) {
  647. if (!files.length) {
  648. return files
  649. }
  650. var accept = this.option("accept");
  651. if (!accept.length) {
  652. return files
  653. }
  654. var result = [];
  655. var allowedTypes = this._getAllowedFileTypes(accept);
  656. for (var i = 0, n = files.length; i < n; i++) {
  657. if (this._isFileTypeAllowed(files[i], allowedTypes)) {
  658. result.push(files[i])
  659. }
  660. }
  661. return result
  662. },
  663. _getAllowedFileTypes: function(acceptSting) {
  664. if (!acceptSting.length) {
  665. return []
  666. }
  667. return acceptSting.split(",").map(function(item) {
  668. return item.trim()
  669. })
  670. },
  671. _isFileTypeAllowed: function(file, allowedTypes) {
  672. for (var i = 0, n = allowedTypes.length; i < n; i++) {
  673. var allowedType = allowedTypes[i];
  674. if ("." === allowedType[0]) {
  675. allowedType = allowedType.replace(".", "\\.");
  676. if (file.name.match(new RegExp(allowedType + "$", "i"))) {
  677. return true
  678. }
  679. } else {
  680. allowedType = allowedType.replace("*", "");
  681. if (file.type.match(new RegExp(allowedType, "i"))) {
  682. return true
  683. }
  684. }
  685. }
  686. return false
  687. },
  688. _renderWrapper: function() {
  689. var $wrapper = $("<div>").addClass(FILEUPLOADER_WRAPPER_CLASS).appendTo(this.$element());
  690. var $container = $("<div>").addClass(FILEUPLOADER_CONTAINER_CLASS).appendTo($wrapper);
  691. this._$content = $("<div>").addClass(FILEUPLOADER_CONTENT_CLASS).appendTo($container)
  692. },
  693. _clean: function() {
  694. this._$fileInput.detach();
  695. delete this._$filesContainer;
  696. if (this._files) {
  697. this._files.forEach(function(file) {
  698. file.$file = null;
  699. file.$statusMessage = null
  700. })
  701. }
  702. this.callBase.apply(this, arguments)
  703. },
  704. _uploadFiles: function() {
  705. if (isFormDataSupported()) {
  706. each(this._files, function(_, file) {
  707. this._uploadFile(file)
  708. }.bind(this))
  709. }
  710. },
  711. _uploadFile: function(file) {
  712. this._uploadStrategy.upload(file)
  713. },
  714. _updateProgressBar: function(file, loadedFileData) {
  715. file.progressBar && file.progressBar.option({
  716. value: loadedFileData.loaded,
  717. showStatus: true
  718. });
  719. this._progressAction({
  720. file: file.value,
  721. segmentSize: loadedFileData.currentSegmentSize,
  722. bytesLoaded: loadedFileData.loaded,
  723. bytesTotal: loadedFileData.total,
  724. event: loadedFileData.event,
  725. request: file.request
  726. })
  727. },
  728. _updateTotalProgress: function(totalFilesSize, totalLoadedFilesSize) {
  729. var progress = totalFilesSize ? Math.round(totalLoadedFilesSize / totalFilesSize * 100) : 0;
  730. this.option("progress", progress);
  731. this._setLoadedSize(totalLoadedFilesSize)
  732. },
  733. _initStatusMessage: function(file) {
  734. file.$statusMessage.css("display", "none")
  735. },
  736. _initCancelButton: function(file) {
  737. file.cancelButton.option("onClick", function() {
  738. this._preventFilesUploading([file]);
  739. this._removeFile(file)
  740. }.bind(this));
  741. var hideCancelButton = function() {
  742. setTimeout(function() {
  743. file.cancelButton.option({
  744. visible: false
  745. })
  746. }, FILEUPLOADER_AFTER_LOAD_DELAY)
  747. };
  748. file.onLoad.add(hideCancelButton);
  749. file.onError.add(hideCancelButton)
  750. },
  751. _createProgressBar: function(fileSize) {
  752. return this._createComponent($("<div>"), ProgressBar, {
  753. value: void 0,
  754. min: 0,
  755. max: fileSize,
  756. statusFormat: function(ratio) {
  757. return Math.round(100 * ratio) + "%"
  758. },
  759. showStatus: false,
  760. statusPosition: "right"
  761. })
  762. },
  763. _getTotalFilesSize: function() {
  764. if (!this._totalFilesSize) {
  765. this._totalFilesSize = 0;
  766. each(this._files, function(_, file) {
  767. this._totalFilesSize += file.value.size
  768. }.bind(this))
  769. }
  770. return this._totalFilesSize
  771. },
  772. _getTotalLoadedFilesSize: function() {
  773. if (!this._totalLoadedFilesSize) {
  774. this._totalLoadedFilesSize = 0;
  775. each(this._files, function(_, file) {
  776. this._totalLoadedFilesSize += file.loadedSize
  777. }.bind(this))
  778. }
  779. return this._totalLoadedFilesSize
  780. },
  781. _setLoadedSize: function(value) {
  782. this._totalLoadedFilesSize = value
  783. },
  784. _recalculateProgress: function() {
  785. this._totalFilesSize = 0;
  786. this._totalLoadedFilesSize = 0;
  787. this._updateTotalProgress(this._getTotalFilesSize(), this._getTotalLoadedFilesSize())
  788. },
  789. _getValidationMessageTarget: function() {
  790. return this._$inputWrapper
  791. },
  792. _optionChanged: function(args) {
  793. var value = args.value;
  794. switch (args.name) {
  795. case "height":
  796. case "width":
  797. this._updateFileNameMaxWidth();
  798. this.callBase(args);
  799. break;
  800. case "value":
  801. !value.length && this._$fileInput.val("");
  802. if (!this._preventRecreatingFiles) {
  803. this._createFiles();
  804. this._renderFiles()
  805. }
  806. this._recalculateProgress();
  807. this.callBase(args);
  808. break;
  809. case "name":
  810. this._initFileInput();
  811. this.callBase(args);
  812. break;
  813. case "accept":
  814. this._initFileInput();
  815. break;
  816. case "multiple":
  817. this._initFileInput();
  818. if (!args.value) {
  819. this.reset()
  820. }
  821. break;
  822. case "selectButtonText":
  823. this._selectButton.option("text", value);
  824. break;
  825. case "uploadButtonText":
  826. this._uploadButton && this._uploadButton.option("text", value);
  827. break;
  828. case "_uploadButtonType":
  829. this._uploadButton && this._uploadButton.option("type", value);
  830. break;
  831. case "maxFileSize":
  832. case "minFileSize":
  833. case "allowedFileExtensions":
  834. case "invalidFileExtensionMessage":
  835. case "invalidMaxFileSizeMessage":
  836. case "invalidMinFileSizeMessage":
  837. case "readyToUploadMessage":
  838. case "uploadedMessage":
  839. case "uploadFailedMessage":
  840. this._invalidate();
  841. break;
  842. case "labelText":
  843. this._$inputLabel.text(value);
  844. break;
  845. case "showFileList":
  846. if (!this._preventRecreatingFiles) {
  847. this._renderFiles()
  848. }
  849. break;
  850. case "chunkSize":
  851. this._setUploadStrategy();
  852. break;
  853. case "uploadUrl":
  854. case "progress":
  855. case "uploadMethod":
  856. case "uploadHeaders":
  857. case "extendSelection":
  858. break;
  859. case "allowCanceling":
  860. case "uploadMode":
  861. this.reset();
  862. this._invalidate();
  863. break;
  864. case "onUploadStarted":
  865. this._createUploadStartedAction();
  866. break;
  867. case "onUploaded":
  868. this._createUploadedAction();
  869. break;
  870. case "onProgress":
  871. this._createProgressAction();
  872. break;
  873. case "onUploadError":
  874. this._createUploadErrorAction();
  875. break;
  876. case "onUploadAborted":
  877. this._createUploadAbortedAction();
  878. break;
  879. case "useNativeInputClick":
  880. this._renderInput();
  881. break;
  882. case "useDragOver":
  883. this._renderDragEvents();
  884. break;
  885. case "nativeDropSupported":
  886. this._invalidate();
  887. break;
  888. default:
  889. this.callBase(args)
  890. }
  891. },
  892. reset: function() {
  893. this.option("value", [])
  894. }
  895. });
  896. var FileBlobReader = Class.inherit({
  897. ctor: function(file, chunkSize) {
  898. this.file = file;
  899. this.chunkSize = chunkSize;
  900. this.index = 0
  901. },
  902. read: function() {
  903. if (!this.file) {
  904. return null
  905. }
  906. var result = this.createBlobResult(this.file, this.index, this.chunkSize);
  907. if (result.isCompleted) {
  908. this.file = null
  909. }
  910. this.index++;
  911. return result
  912. },
  913. createBlobResult: function(file, index, chunkSize) {
  914. var currentPosition = index * chunkSize;
  915. return {
  916. blob: this.sliceFile(file, currentPosition, chunkSize),
  917. index: index,
  918. isCompleted: currentPosition + chunkSize >= file.size
  919. }
  920. },
  921. sliceFile: function(file, startPos, length) {
  922. if (file.slice) {
  923. return file.slice(startPos, startPos + length)
  924. }
  925. if (file.webkitSlice) {
  926. return file.webkitSlice(startPos, startPos + length)
  927. }
  928. return null
  929. }
  930. });
  931. var FileUploadStrategyBase = Class.inherit({
  932. ctor: function(fileUploader) {
  933. this.fileUploader = fileUploader
  934. },
  935. upload: function(file) {
  936. if (file.isValid() && !file.uploadStarted) {
  937. this._prepareFileBeforeUpload(file);
  938. this._uploadCore(file)
  939. }
  940. },
  941. _uploadCore: function(file) {},
  942. _prepareFileBeforeUpload: function(file) {
  943. if (file.$file) {
  944. this.fileUploader._createFileProgressBar(file)
  945. }
  946. file.onLoadStart.add(this._onUploadStarted.bind(this, file));
  947. file.onLoad.add(this._onLoadedHandler.bind(this, file));
  948. file.onError.add(this._onErrorHandler.bind(this, file));
  949. file.onAbort.add(this._onAbortHandler.bind(this, file));
  950. file.onProgress.add(this._onProgressHandler.bind(this, file))
  951. },
  952. _isStatusError: function(status) {
  953. return 400 <= status && status < 500 || 500 <= status && status < 600
  954. },
  955. _onUploadStarted: function(file, e) {
  956. file.uploadStarted = true;
  957. this.fileUploader._uploadStartedAction({
  958. file: file.value,
  959. event: e,
  960. request: file.request
  961. })
  962. },
  963. _onAbortHandler: function(file, e) {
  964. this.fileUploader._uploadAbortedAction({
  965. file: file.value,
  966. event: e,
  967. request: file.request
  968. })
  969. },
  970. _onErrorHandler: function(file, e) {
  971. this.fileUploader._setStatusMessage(file, "uploadFailedMessage");
  972. this.fileUploader._uploadErrorAction({
  973. file: file.value,
  974. event: e,
  975. request: file.request
  976. })
  977. },
  978. _onLoadedHandler: function(file, e) {
  979. this.fileUploader._setStatusMessage(file, "uploadedMessage");
  980. this.fileUploader._uploadedAction({
  981. file: file.value,
  982. event: e,
  983. request: file.request
  984. })
  985. },
  986. _onProgressHandler: function(file, e) {
  987. if (file) {
  988. var totalFilesSize = this.fileUploader._getTotalFilesSize();
  989. var totalLoadedFilesSize = this.fileUploader._getTotalLoadedFilesSize();
  990. var loadedSize = Math.min(e.loaded, file.value.size);
  991. var segmentSize = loadedSize - file.loadedSize;
  992. file.loadedSize = loadedSize;
  993. this.fileUploader._updateTotalProgress(totalFilesSize, totalLoadedFilesSize + segmentSize);
  994. this.fileUploader._updateProgressBar(file, this._getLoadedData(loadedSize, e.total, segmentSize, e))
  995. }
  996. },
  997. _getLoadedData: function(loaded, total, currentSegmentSize, event) {
  998. return {
  999. loaded: loaded,
  1000. total: total,
  1001. currentSegmentSize: currentSegmentSize
  1002. }
  1003. }
  1004. });
  1005. var ChunksFileUploadStrategy = FileUploadStrategyBase.inherit({
  1006. ctor: function(fileUploader) {
  1007. this.callBase(fileUploader);
  1008. this.chunkSize = this.fileUploader.option("chunkSize")
  1009. },
  1010. _uploadCore: function(file) {
  1011. var realFile = file.value;
  1012. this._sendChunk(file, {
  1013. name: realFile.name,
  1014. loadedBytes: 0,
  1015. type: realFile.type,
  1016. blobReader: new FileBlobReader(realFile, this.chunkSize),
  1017. guid: new Guid,
  1018. fileSize: realFile.size,
  1019. count: Math.ceil(realFile.size / this.chunkSize)
  1020. })
  1021. },
  1022. _sendChunk: function(file, chunksData) {
  1023. var chunk = chunksData.blobReader.read();
  1024. if (chunk) {
  1025. chunksData.loadedBytes += chunk.blob.size;
  1026. ajax.sendRequest({
  1027. url: this.fileUploader.option("uploadUrl"),
  1028. method: this.fileUploader.option("uploadMethod"),
  1029. headers: this.fileUploader.option("uploadHeaders"),
  1030. beforeSend: function(xhr) {
  1031. file.request = xhr
  1032. },
  1033. upload: {
  1034. onloadstart: function() {
  1035. if (!file.isStartLoad) {
  1036. file.isStartLoad = true;
  1037. file.onLoadStart.fire()
  1038. }
  1039. },
  1040. onabort: function() {
  1041. file.onAbort.fire()
  1042. }
  1043. },
  1044. data: this._createFormData({
  1045. fileName: chunksData.name,
  1046. blobName: this.fileUploader.option("name"),
  1047. blob: chunk.blob,
  1048. index: chunk.index,
  1049. count: chunksData.count,
  1050. type: chunksData.type,
  1051. guid: chunksData.guid,
  1052. size: chunksData.fileSize
  1053. })
  1054. }).done(function() {
  1055. file.onProgress.fire({
  1056. loaded: chunksData.loadedBytes,
  1057. total: file.value.size
  1058. });
  1059. if (chunk.isCompleted) {
  1060. file.onLoad.fire()
  1061. }
  1062. this._sendChunk(file, chunksData)
  1063. }.bind(this)).fail(function(e) {
  1064. if (this._isStatusError(e.status)) {
  1065. file._isError = true;
  1066. file.onError.fire()
  1067. }
  1068. }.bind(this))
  1069. }
  1070. },
  1071. _createFormData: function(options) {
  1072. var formData = new window.FormData;
  1073. formData.append(options.blobName, options.blob);
  1074. formData.append(FILEUPLOADER_CHUNK_META_DATA_NAME, JSON.stringify({
  1075. FileName: options.fileName,
  1076. Index: options.index,
  1077. TotalCount: options.count,
  1078. FileSize: options.size,
  1079. FileType: options.type,
  1080. FileGuid: options.guid
  1081. }));
  1082. return formData
  1083. },
  1084. _getEvent: function(e) {
  1085. return null
  1086. }
  1087. });
  1088. var WholeFileUploadStrategy = FileUploadStrategyBase.inherit({
  1089. _uploadCore: function(file) {
  1090. file.loadedSize = 0;
  1091. ajax.sendRequest({
  1092. url: this.fileUploader.option("uploadUrl"),
  1093. method: this.fileUploader.option("uploadMethod"),
  1094. headers: this.fileUploader.option("uploadHeaders"),
  1095. beforeSend: function(xhr) {
  1096. file.request = xhr
  1097. },
  1098. upload: {
  1099. onprogress: function(e) {
  1100. if (file._isError) {
  1101. return
  1102. }
  1103. file._isProgressStarted = true;
  1104. file.onProgress.fire(e)
  1105. },
  1106. onloadstart: function() {
  1107. file.onLoadStart.fire()
  1108. },
  1109. onabort: function() {
  1110. file.onAbort.fire()
  1111. }
  1112. },
  1113. data: this._createFormData(this.fileUploader.option("name"), file.value)
  1114. }).done(function() {
  1115. file.onLoad.fire()
  1116. }).fail(function(e) {
  1117. if (this._isStatusError(e.status) || !file._isProgressStarted) {
  1118. file._isError = true;
  1119. file.onError.fire()
  1120. }
  1121. }.bind(this))
  1122. },
  1123. _createFormData: function(fieldName, fieldValue) {
  1124. var formData = new window.FormData;
  1125. formData.append(fieldName, fieldValue);
  1126. return formData
  1127. },
  1128. _getLoadedData: function(loaded, total, segmentSize, event) {
  1129. var result = this.callBase(loaded, total, segmentSize, event);
  1130. result.event = event;
  1131. return result
  1132. }
  1133. });
  1134. registerComponent("dxFileUploader", FileUploader);
  1135. module.exports = FileUploader;
  1136. module.exports.default = module.exports;