trumbowyg.upload.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /* ===========================================================
  2. * trumbowyg.upload.js v1.2
  3. * Upload plugin for Trumbowyg
  4. * http://alex-d.github.com/Trumbowyg
  5. * ===========================================================
  6. * Author : Alexandre Demode (Alex-D)
  7. * Twitter : @AlexandreDemode
  8. * Website : alex-d.fr
  9. * Mod by : Aleksandr-ru
  10. * Twitter : @Aleksandr_ru
  11. * Website : aleksandr.ru
  12. */
  13. (function ($) {
  14. 'use strict';
  15. var defaultOptions = {
  16. serverPath: '',
  17. fileFieldName: 'fileToUpload',
  18. data: [], // Additional data for ajax [{name: 'key', value: 'value'}]
  19. headers: {}, // Additional headers
  20. xhrFields: {}, // Additional fields
  21. urlPropertyName: 'file', // How to get url from the json response (for instance 'url' for {url: ....})
  22. statusPropertyName: 'success', // How to get status from the json response
  23. success: undefined, // Success callback: function (data, trumbowyg, $modal, values) {}
  24. error: undefined, // Error callback: function () {}
  25. imageWidthModalEdit: false // Add ability to edit image width
  26. };
  27. function getDeep(object, propertyParts) {
  28. var mainProperty = propertyParts.shift(),
  29. otherProperties = propertyParts;
  30. if (object !== null) {
  31. if (otherProperties.length === 0) {
  32. return object[mainProperty];
  33. }
  34. if (typeof object === 'object') {
  35. return getDeep(object[mainProperty], otherProperties);
  36. }
  37. }
  38. return object;
  39. }
  40. addXhrProgressEvent();
  41. $.extend(true, $.trumbowyg, {
  42. langs: {
  43. // jshint camelcase:false
  44. en: {
  45. upload: 'Upload',
  46. file: 'File',
  47. uploadError: 'Error'
  48. },
  49. cs: {
  50. upload: 'Nahrát obrázek',
  51. file: 'Soubor',
  52. uploadError: 'Chyba'
  53. },
  54. da: {
  55. upload: 'Upload',
  56. file: 'Fil',
  57. uploadError: 'Fejl'
  58. },
  59. de: {
  60. upload: 'Hochladen',
  61. file: 'Datei',
  62. uploadError: 'Fehler'
  63. },
  64. fr: {
  65. upload: 'Envoi',
  66. file: 'Fichier',
  67. uploadError: 'Erreur'
  68. },
  69. hu: {
  70. upload: 'Feltöltés',
  71. file: 'Fájl',
  72. uploadError: 'Hiba'
  73. },
  74. ja: {
  75. upload: 'アップロード',
  76. file: 'ファイル',
  77. uploadError: 'エラー'
  78. },
  79. ko: {
  80. upload: '그림 올리기',
  81. file: '파일',
  82. uploadError: '에러'
  83. },
  84. pt_br: {
  85. upload: 'Enviar do local',
  86. file: 'Arquivo',
  87. uploadError: 'Erro'
  88. },
  89. ru: {
  90. upload: 'Загрузка',
  91. file: 'Файл',
  92. uploadError: 'Ошибка'
  93. },
  94. sk: {
  95. upload: 'Nahrať',
  96. file: 'Súbor',
  97. uploadError: 'Chyba'
  98. },
  99. tr: {
  100. upload: 'Yükle',
  101. file: 'Dosya',
  102. uploadError: 'Hata'
  103. },
  104. zh_cn: {
  105. upload: '上传',
  106. file: '文件',
  107. uploadError: '错误'
  108. },
  109. zh_tw: {
  110. upload: '上傳',
  111. file: '文件',
  112. uploadError: '錯誤'
  113. },
  114. },
  115. // jshint camelcase:true
  116. plugins: {
  117. upload: {
  118. init: function (trumbowyg) {
  119. trumbowyg.o.plugins.upload = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.upload || {});
  120. var btnDef = {
  121. fn: function () {
  122. trumbowyg.saveRange();
  123. var file,
  124. prefix = trumbowyg.o.prefix;
  125. var fields = {
  126. file: {
  127. type: 'file',
  128. required: true,
  129. attributes: {
  130. accept: 'image/*'
  131. }
  132. },
  133. alt: {
  134. label: 'description',
  135. value: trumbowyg.getRangeText()
  136. }
  137. };
  138. if (trumbowyg.o.plugins.upload.imageWidthModalEdit) {
  139. fields.width = {
  140. value: ''
  141. };
  142. }
  143. // Prevent multiple submissions while uploading
  144. var isUploading = false;
  145. var $modal = trumbowyg.openModalInsert(
  146. // Title
  147. trumbowyg.lang.upload,
  148. // Fields
  149. fields,
  150. // Callback
  151. function (values) {
  152. if (isUploading) {
  153. return;
  154. }
  155. isUploading = true;
  156. var data = new FormData();
  157. data.append(trumbowyg.o.plugins.upload.fileFieldName, file);
  158. trumbowyg.o.plugins.upload.data.map(function (cur) {
  159. data.append(cur.name, cur.value);
  160. });
  161. $.map(values, function (curr, key) {
  162. if (key !== 'file') {
  163. data.append(key, curr);
  164. }
  165. });
  166. if ($('.' + prefix + 'progress', $modal).length === 0) {
  167. $('.' + prefix + 'modal-title', $modal)
  168. .after(
  169. $('<div/>', {
  170. 'class': prefix + 'progress'
  171. }).append(
  172. $('<div/>', {
  173. 'class': prefix + 'progress-bar'
  174. })
  175. )
  176. );
  177. }
  178. $.ajax({
  179. url: trumbowyg.o.plugins.upload.serverPath,
  180. headers: trumbowyg.o.plugins.upload.headers,
  181. xhrFields: trumbowyg.o.plugins.upload.xhrFields,
  182. type: 'POST',
  183. data: data,
  184. cache: false,
  185. dataType: 'json',
  186. processData: false,
  187. contentType: false,
  188. progressUpload: function (e) {
  189. $('.' + prefix + 'progress-bar').css('width', Math.round(e.loaded * 100 / e.total) + '%');
  190. },
  191. success: function (data) {
  192. if (trumbowyg.o.plugins.upload.success) {
  193. trumbowyg.o.plugins.upload.success(data, trumbowyg, $modal, values);
  194. } else {
  195. if (!!getDeep(data, trumbowyg.o.plugins.upload.statusPropertyName.split('.'))) {
  196. var url = getDeep(data, trumbowyg.o.plugins.upload.urlPropertyName.split('.'));
  197. trumbowyg.execCmd('insertImage', url, false, true);
  198. var $img = $('img[src="' + url + '"]:not([alt])', trumbowyg.$box);
  199. $img.attr('alt', values.alt);
  200. if (trumbowyg.o.plugins.upload.imageWidthModalEdit && parseInt(values.width) > 0) {
  201. $img.attr({
  202. width: values.width
  203. });
  204. }
  205. setTimeout(function () {
  206. trumbowyg.closeModal();
  207. }, 250);
  208. trumbowyg.$c.trigger('tbwuploadsuccess', [trumbowyg, data, url]);
  209. } else {
  210. trumbowyg.addErrorOnModalField(
  211. $('input[type=file]', $modal),
  212. trumbowyg.lang[data.message]
  213. );
  214. trumbowyg.$c.trigger('tbwuploaderror', [trumbowyg, data]);
  215. }
  216. }
  217. isUploading = false;
  218. },
  219. error: trumbowyg.o.plugins.upload.error || function () {
  220. trumbowyg.addErrorOnModalField(
  221. $('input[type=file]', $modal),
  222. trumbowyg.lang.uploadError
  223. );
  224. trumbowyg.$c.trigger('tbwuploaderror', [trumbowyg]);
  225. isUploading = false;
  226. }
  227. });
  228. }
  229. );
  230. $('input[type=file]').on('change', function (e) {
  231. try {
  232. // If multiple files allowed, we just get the first.
  233. file = e.target.files[0];
  234. } catch (err) {
  235. // In IE8, multiple files not allowed
  236. file = e.target.value;
  237. }
  238. });
  239. }
  240. };
  241. trumbowyg.addBtnDef('upload', btnDef);
  242. }
  243. }
  244. }
  245. });
  246. function addXhrProgressEvent() {
  247. if (!$.trumbowyg.addedXhrProgressEvent) { // Avoid adding progress event multiple times
  248. var originalXhr = $.ajaxSettings.xhr;
  249. $.ajaxSetup({
  250. xhr: function () {
  251. var that = this,
  252. req = originalXhr();
  253. if (req && typeof req.upload === 'object' && that.progressUpload !== undefined) {
  254. req.upload.addEventListener('progress', function (e) {
  255. that.progressUpload(e);
  256. }, false);
  257. }
  258. return req;
  259. }
  260. });
  261. $.trumbowyg.addedXhrProgressEvent = true;
  262. }
  263. }
  264. })(jQuery);