trumbowyg.upload.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. da: {
  50. upload: 'Upload',
  51. file: 'Fil',
  52. uploadError: 'Fejl'
  53. },
  54. sk: {
  55. upload: 'Nahrať',
  56. file: 'Súbor',
  57. uploadError: 'Chyba'
  58. },
  59. fr: {
  60. upload: 'Envoi',
  61. file: 'Fichier',
  62. uploadError: 'Erreur'
  63. },
  64. cs: {
  65. upload: 'Nahrát obrázek',
  66. file: 'Soubor',
  67. uploadError: 'Chyba'
  68. },
  69. zh_cn: {
  70. upload: '上传',
  71. file: '文件',
  72. uploadError: '错误'
  73. },
  74. zh_tw: {
  75. upload: '上傳',
  76. file: '文件',
  77. uploadError: '錯誤'
  78. },
  79. ru: {
  80. upload: 'Загрузка',
  81. file: 'Файл',
  82. uploadError: 'Ошибка'
  83. },
  84. ja: {
  85. upload: 'アップロード',
  86. file: 'ファイル',
  87. uploadError: 'エラー'
  88. },
  89. pt_br: {
  90. upload: 'Enviar do local',
  91. file: 'Arquivo',
  92. uploadError: 'Erro'
  93. },
  94. tr: {
  95. upload: 'Yükle',
  96. file: 'Dosya',
  97. uploadError: 'Hata'
  98. }
  99. },
  100. // jshint camelcase:true
  101. plugins: {
  102. upload: {
  103. init: function (trumbowyg) {
  104. trumbowyg.o.plugins.upload = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.upload || {});
  105. var btnDef = {
  106. fn: function () {
  107. trumbowyg.saveRange();
  108. var file,
  109. prefix = trumbowyg.o.prefix;
  110. var fields = {
  111. file: {
  112. type: 'file',
  113. required: true,
  114. attributes: {
  115. accept: 'image/*'
  116. }
  117. },
  118. alt: {
  119. label: 'description',
  120. value: trumbowyg.getRangeText()
  121. }
  122. };
  123. if (trumbowyg.o.plugins.upload.imageWidthModalEdit) {
  124. fields.width = {
  125. value: ''
  126. };
  127. }
  128. var $modal = trumbowyg.openModalInsert(
  129. // Title
  130. trumbowyg.lang.upload,
  131. // Fields
  132. fields,
  133. // Callback
  134. function (values) {
  135. var data = new FormData();
  136. data.append(trumbowyg.o.plugins.upload.fileFieldName, file);
  137. trumbowyg.o.plugins.upload.data.map(function (cur) {
  138. data.append(cur.name, cur.value);
  139. });
  140. $.map(values, function (curr, key) {
  141. if (key !== 'file') {
  142. data.append(key, curr);
  143. }
  144. });
  145. if ($('.' + prefix + 'progress', $modal).length === 0) {
  146. $('.' + prefix + 'modal-title', $modal)
  147. .after(
  148. $('<div/>', {
  149. 'class': prefix + 'progress'
  150. }).append(
  151. $('<div/>', {
  152. 'class': prefix + 'progress-bar'
  153. })
  154. )
  155. );
  156. }
  157. $.ajax({
  158. url: trumbowyg.o.plugins.upload.serverPath,
  159. headers: trumbowyg.o.plugins.upload.headers,
  160. xhrFields: trumbowyg.o.plugins.upload.xhrFields,
  161. type: 'POST',
  162. data: data,
  163. cache: false,
  164. dataType: 'json',
  165. processData: false,
  166. contentType: false,
  167. progressUpload: function (e) {
  168. $('.' + prefix + 'progress-bar').css('width', Math.round(e.loaded * 100 / e.total) + '%');
  169. },
  170. success: function (data) {
  171. if (trumbowyg.o.plugins.upload.success) {
  172. trumbowyg.o.plugins.upload.success(data, trumbowyg, $modal, values);
  173. } else {
  174. if (!!getDeep(data, trumbowyg.o.plugins.upload.statusPropertyName.split('.'))) {
  175. var url = getDeep(data, trumbowyg.o.plugins.upload.urlPropertyName.split('.'));
  176. trumbowyg.execCmd('insertImage', url, false, true);
  177. var $img = $('img[src="' + url + '"]:not([alt])', trumbowyg.$box);
  178. $img.attr('alt', values.alt);
  179. if (trumbowyg.o.imageWidthModalEdit && parseInt(values.width) > 0) {
  180. $img.attr({
  181. width: values.width
  182. });
  183. }
  184. setTimeout(function () {
  185. trumbowyg.closeModal();
  186. }, 250);
  187. trumbowyg.$c.trigger('tbwuploadsuccess', [trumbowyg, data, url]);
  188. } else {
  189. trumbowyg.addErrorOnModalField(
  190. $('input[type=file]', $modal),
  191. trumbowyg.lang[data.message]
  192. );
  193. trumbowyg.$c.trigger('tbwuploaderror', [trumbowyg, data]);
  194. }
  195. }
  196. },
  197. error: trumbowyg.o.plugins.upload.error || function () {
  198. trumbowyg.addErrorOnModalField(
  199. $('input[type=file]', $modal),
  200. trumbowyg.lang.uploadError
  201. );
  202. trumbowyg.$c.trigger('tbwuploaderror', [trumbowyg]);
  203. }
  204. });
  205. }
  206. );
  207. $('input[type=file]').on('change', function (e) {
  208. try {
  209. // If multiple files allowed, we just get the first.
  210. file = e.target.files[0];
  211. } catch (err) {
  212. // In IE8, multiple files not allowed
  213. file = e.target.value;
  214. }
  215. });
  216. }
  217. };
  218. trumbowyg.addBtnDef('upload', btnDef);
  219. }
  220. }
  221. }
  222. });
  223. function addXhrProgressEvent() {
  224. if (!$.trumbowyg.addedXhrProgressEvent) { // Avoid adding progress event multiple times
  225. var originalXhr = $.ajaxSettings.xhr;
  226. $.ajaxSetup({
  227. xhr: function () {
  228. var req = originalXhr(),
  229. that = this;
  230. if (req && typeof req.upload === 'object' && that.progressUpload !== undefined) {
  231. req.upload.addEventListener('progress', function (e) {
  232. that.progressUpload(e);
  233. }, false);
  234. }
  235. return req;
  236. }
  237. });
  238. $.trumbowyg.addedXhrProgressEvent = true;
  239. }
  240. }
  241. })(jQuery);