require-upload.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. define(['jquery', 'bootstrap', 'dropzone', 'template'], function ($, undefined, Dropzone, Template) {
  2. var Upload = {
  3. list: {},
  4. options: {},
  5. config: {
  6. container: document.body,
  7. classname: '.plupload:not([initialized]),.faupload:not([initialized])',
  8. previewtpl: '<li class="col-xs-3"><a href="<%=fullurl%>" data-url="<%=url%>" target="_blank" class="thumbnail"><img src="<%=fullurl%>" onerror="this.src=\'' + Fast.api.fixurl("ajax/icon") + '?suffix=<%=suffix%>\';this.onerror=null;" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>',
  9. },
  10. events: {
  11. //初始化
  12. onInit: function () {
  13. },
  14. //上传成功的回调
  15. onUploadSuccess: function (up, ret, file) {
  16. var button = up.element;
  17. var onUploadSuccess = up.options.onUploadSuccess;
  18. var data = typeof ret.data !== 'undefined' ? ret.data : null;
  19. //上传成功后回调
  20. if (button) {
  21. //如果有文本框则填充
  22. var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
  23. if (input_id) {
  24. var urlArr = [];
  25. var inputObj = $("#" + input_id);
  26. if ($(button).data("multiple") && inputObj.val() !== "") {
  27. urlArr.push(inputObj.val());
  28. }
  29. urlArr.push(data.url);
  30. inputObj.val(urlArr.join(",")).trigger("change").trigger("validate");
  31. }
  32. //如果有回调函数
  33. var onDomUploadSuccess = $(button).data("upload-success");
  34. if (onDomUploadSuccess) {
  35. if (typeof onDomUploadSuccess !== 'function' && typeof Upload.api.custom[onDomUploadSuccess] === 'function') {
  36. onDomUploadSuccess = Upload.api.custom[onDomUploadSuccess];
  37. }
  38. if (typeof onDomUploadSuccess === 'function') {
  39. var result = onDomUploadSuccess.call(button, data, ret);
  40. if (result === false)
  41. return;
  42. }
  43. }
  44. }
  45. if (typeof onUploadSuccess === 'function') {
  46. var result = onUploadSuccess.call(button, data, ret);
  47. if (result === false)
  48. return;
  49. }
  50. },
  51. //上传错误的回调
  52. onUploadError: function (up, ret, file) {
  53. var button = up.element;
  54. var onUploadError = up.options.onUploadError;
  55. var data = typeof ret.data !== 'undefined' ? ret.data : null;
  56. if (button) {
  57. var onDomUploadError = $(button).data("upload-error");
  58. if (onDomUploadError) {
  59. if (typeof onDomUploadError !== 'function' && typeof Upload.api.custom[onDomUploadError] === 'function') {
  60. onDomUploadError = Upload.api.custom[onDomUploadError];
  61. }
  62. if (typeof onDomUploadError === 'function') {
  63. var result = onDomUploadError.call(button, data, ret);
  64. if (result === false)
  65. return;
  66. }
  67. }
  68. }
  69. if (typeof onUploadError === 'function') {
  70. var result = onUploadError.call(button, data, ret);
  71. if (result === false) {
  72. return;
  73. }
  74. }
  75. Toastr.error(ret.msg.toString().replace(/(<([^>]+)>)/gi, "") + "(code:" + ret.code + ")");
  76. },
  77. //服务器响应数据后
  78. onUploadResponse: function (response, up, file) {
  79. try {
  80. var ret = typeof response === 'object' ? response : JSON.parse(response);
  81. if (!ret.hasOwnProperty('code')) {
  82. $.extend(ret, {code: -2, msg: response, data: null});
  83. }
  84. } catch (e) {
  85. var ret = {code: -1, msg: e.message, data: null};
  86. }
  87. return ret;
  88. },
  89. //上传全部结束后
  90. onUploadComplete: function (up, files) {
  91. var button = up.element;
  92. var onUploadComplete = up.options.onUploadComplete;
  93. if (button) {
  94. var onDomUploadComplete = $(button).data("upload-complete");
  95. if (onDomUploadComplete) {
  96. if (typeof onDomUploadComplete !== 'function' && typeof Upload.api.custom[onDomUploadComplete] === 'function') {
  97. onDomUploadComplete = Upload.api.custom[onDomUploadComplete];
  98. }
  99. if (typeof onDomUploadComplete === 'function') {
  100. var result = onDomUploadComplete.call(button, files);
  101. if (result === false)
  102. return;
  103. }
  104. }
  105. }
  106. if (typeof onUploadComplete === 'function') {
  107. var result = onUploadComplete.call(button, files);
  108. if (result === false) {
  109. return;
  110. }
  111. }
  112. }
  113. },
  114. api: {
  115. //上传接口
  116. upload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
  117. element = typeof element === 'undefined' ? Upload.config.classname : element;
  118. $(element, Upload.config.container).each(function () {
  119. if ($(this).attr("initialized")) {
  120. return true;
  121. }
  122. $(this).attr("initialized", true);
  123. var that = this;
  124. var id = $(this).prop("id") || $(this).prop("name") || Dropzone.uuidv4();
  125. var url = $(this).data("url");
  126. var maxsize = $(this).data("maxsize");
  127. var maxcount = $(this).data("maxcount");
  128. var mimetype = $(this).data("mimetype");
  129. var multipart = $(this).data("multipart");
  130. var multiple = $(this).data("multiple");
  131. //填充ID
  132. var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
  133. //预览ID
  134. var preview_id = $(that).data("preview-id") ? $(that).data("preview-id") : "";
  135. //上传URL
  136. url = url ? url : Config.upload.uploadurl;
  137. url = Fast.api.fixurl(url);
  138. var chunking = false, chunkSize = Config.upload.chunksize || 2097152, timeout = Config.upload.timeout || 600000;
  139. //最大可上传文件大小
  140. maxsize = typeof maxsize !== "undefined" ? maxsize : Config.upload.maxsize;
  141. //文件类型
  142. mimetype = typeof mimetype !== "undefined" ? mimetype : Config.upload.mimetype;
  143. //请求的表单参数
  144. multipart = typeof multipart !== "undefined" ? multipart : Config.upload.multipart;
  145. //是否支持批量上传
  146. multiple = typeof multiple !== "undefined" ? multiple : Config.upload.multiple;
  147. //后缀特殊处理
  148. mimetype = mimetype.split(",").map(function (k) {
  149. return k.indexOf("/") > -1 ? k : (!k || k === "*" || k.charAt(0) === "." ? k : "." + k);
  150. }).join(",");
  151. mimetype = mimetype === '*' ? null : mimetype;
  152. //最大文件限制转换成mb
  153. var maxFilesize = (function (maxsize) {
  154. var matches = maxsize.toString().match(/^([0-9\.]+)(\w+)$/);
  155. var size = matches ? parseFloat(matches[1]) : parseFloat(maxsize),
  156. unit = matches ? matches[2].toLowerCase() : 'b';
  157. var unitDict = {'b': 0, 'k': 1, 'kb': 1, 'm': 2, 'mb': 2, 'gb': 3, 'g': 3, 'tb': 4, 't': 4};
  158. var y = typeof unitDict[unit] !== 'undefined' ? unitDict[unit] : 0;
  159. var bytes = size * Math.pow(1024, y);
  160. return bytes / Math.pow(1024, 2);
  161. }(maxsize));
  162. var options = $(this).data() || {};
  163. delete options.success;
  164. delete options.url;
  165. multipart = $.isArray(multipart) ? {} : multipart;
  166. Upload.list[id] = new Dropzone(this, $.extend({
  167. url: url,
  168. params: function (files, xhr, chunk) {
  169. var params = multipart;
  170. if (chunk) {
  171. return $.extend({}, params, {
  172. filesize: chunk.file.size,
  173. filename: chunk.file.name,
  174. chunkid: chunk.file.upload.uuid,
  175. chunkindex: chunk.index,
  176. chunkcount: chunk.file.upload.totalChunkCount,
  177. chunksize: this.options.chunkSize,
  178. chunkfilesize: chunk.dataBlock.data.size,
  179. width: chunk.file.width || 0,
  180. height: chunk.file.height || 0,
  181. type: chunk.file.type,
  182. });
  183. }
  184. return params;
  185. },
  186. chunking: chunking,
  187. chunkSize: chunkSize,
  188. maxFilesize: maxFilesize,
  189. acceptedFiles: mimetype,
  190. maxFiles: (maxcount && parseInt(maxcount) > 1 ? maxcount : (multiple ? null : 1)),
  191. timeout: timeout,
  192. parallelUploads: 1,
  193. previewsContainer: false,
  194. dictDefaultMessage: __("Drop files here to upload"),
  195. dictFallbackMessage: __("Your browser does not support drag'n'drop file uploads"),
  196. dictFallbackText: __("Please use the fallback form below to upload your files like in the olden days"),
  197. dictFileTooBig: __("File is too big (%sMiB), Max filesize: %sMiB", "{{filesize}}", "{{maxFilesize}}"),
  198. dictInvalidFileType: __("You can't upload files of this type"),
  199. dictResponseError: __("Server responded with %s code.", "{{statusCode}}"),
  200. dictCancelUpload: __("Cancel upload"),
  201. dictUploadCanceled: __("Upload canceled"),
  202. dictCancelUploadConfirmation: __("Are you sure you want to cancel this upload?"),
  203. dictRemoveFile: __("Remove file"),
  204. dictMaxFilesExceeded: __("You can only upload a maximum of %s files", "{{maxFiles}}"),
  205. init: function () {
  206. Upload.events.onInit.call(this);
  207. //必须添加dz-message,否则点击icon无法唤起上传窗口
  208. $(">i", this.element).addClass("dz-message");
  209. this.options.elementHtml = $(this.element).html();
  210. },
  211. addedfiles: function (files) {
  212. if (this.options.maxFiles && (!this.options.maxFiles || this.options.maxFiles > 1) && this.options.inputId) {
  213. var inputObj = $("#" + this.options.inputId);
  214. if (inputObj.size() > 0) {
  215. var value = $.trim(inputObj.val());
  216. var nums = value === '' ? 0 : value.split(/\,/).length;
  217. var remain = this.options.maxFiles - nums;
  218. if (remain === 0 || files.length > remain) {
  219. files = Array.prototype.slice.call(files, remain);
  220. for (var i = 0; i < files.length; i++) {
  221. this.removeFile(files[i]);
  222. }
  223. Toastr.error(__("You can only upload a maximum of %s files", this.options.maxFiles));
  224. }
  225. }
  226. }
  227. },
  228. success: function (file, response) {
  229. var ret = Upload.events.onUploadResponse(response, this, file);
  230. file.ret = ret;
  231. if (ret.code === 1) {
  232. Upload.events.onUploadSuccess(this, ret, file);
  233. } else {
  234. Upload.events.onUploadError(this, ret, file);
  235. }
  236. },
  237. error: function (file, response, xhr) {
  238. var responseObj = $("<div>" + (xhr && typeof xhr.responseText !== 'undefined' ? xhr.responseText : response) + "</div>");
  239. responseObj.find("style, title, script").remove();
  240. var ret = {code: 0, data: null, msg: responseObj.text()};
  241. Upload.events.onUploadError(this, ret, file);
  242. },
  243. uploadprogress: function (file, progress, bytesSent) {
  244. if (file.upload.chunked) {
  245. $(this.element).prop("disabled", true).html("<i class='fa fa-upload'></i> " + __('Upload') + Math.floor((file.upload.bytesSent / file.size) * 100) + "%");
  246. }
  247. },
  248. totaluploadprogress: function (progress, bytesSent) {
  249. if (this.getActiveFiles().length > 0 && !this.options.chunking) {
  250. $(this.element).prop("disabled", true).html("<i class='fa fa-upload'></i> " + __('Upload') + Math.floor(progress) + "%");
  251. }
  252. },
  253. queuecomplete: function () {
  254. Upload.events.onUploadComplete(this, this.files);
  255. this.removeAllFiles(true);
  256. $(this.element).prop("disabled", false).html(this.options.elementHtml);
  257. },
  258. chunkSuccess: function (chunk, file, response) {
  259. },
  260. chunksUploaded: function (file, done) {
  261. var that = this;
  262. Fast.api.ajax({
  263. url: this.options.url,
  264. data: $.extend({}, multipart, {
  265. action: 'merge',
  266. filesize: file.size,
  267. filename: file.name,
  268. chunkid: file.upload.uuid,
  269. chunkcount: file.upload.totalChunkCount,
  270. })
  271. }, function (data, ret) {
  272. done(JSON.stringify(ret));
  273. return false;
  274. }, function (data, ret) {
  275. file.accepted = false;
  276. that._errorProcessing([file], ret.msg);
  277. });
  278. },
  279. onUploadSuccess: onUploadSuccess,
  280. onUploadError: onUploadError,
  281. onUploadComplete: onUploadComplete,
  282. }, Upload.options, options));
  283. //拖动排序
  284. if (preview_id && multiple) {
  285. require(['dragsort'], function () {
  286. $("#" + preview_id).dragsort({
  287. dragSelector: "li a:not(.btn-trash)",
  288. dragEnd: function () {
  289. $("#" + preview_id).trigger("fa.preview.change");
  290. },
  291. placeHolderTemplate: '<li class="col-xs-3"></li>'
  292. });
  293. });
  294. }
  295. //刷新隐藏textarea的值
  296. var refresh = function (name) {
  297. var data = {};
  298. var textarea = $("textarea[name='" + name + "']");
  299. var container = textarea.prev("ul");
  300. $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
  301. var reg = /\[?(\w+)\]?\[(\w+)\]$/g;
  302. var match = reg.exec(j.name);
  303. if (!match)
  304. return true;
  305. if (!isNaN(match[2])) {
  306. data[i] = j.value;
  307. } else {
  308. match[1] = "x" + parseInt(match[1]);
  309. if (typeof data[match[1]] === 'undefined') {
  310. data[match[1]] = {};
  311. }
  312. data[match[1]][match[2]] = j.value;
  313. }
  314. });
  315. var result = [];
  316. $.each(data, function (i, j) {
  317. result.push(j);
  318. });
  319. textarea.val(JSON.stringify(result));
  320. };
  321. if (preview_id && input_id) {
  322. $(document.body).on("keyup change", "#" + input_id, function (e) {
  323. var inputStr = $("#" + input_id).val();
  324. var inputArr = inputStr.split(/\,/);
  325. $("#" + preview_id).empty();
  326. var tpl = $("#" + preview_id).data("template") ? $("#" + preview_id).data("template") : "";
  327. var extend = $("#" + preview_id).next().is("textarea") ? $("#" + preview_id).next("textarea").val() : "{}";
  328. var json = {};
  329. try {
  330. json = JSON.parse(extend);
  331. } catch (e) {
  332. }
  333. $.each(inputArr, function (i, j) {
  334. if (!j) {
  335. return true;
  336. }
  337. var suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(j);
  338. suffix = suffix ? suffix[1] : 'file';
  339. var value = (json && typeof json[i] !== 'undefined' ? json[i] : null);
  340. var data = {url: j, fullurl: Fast.api.cdnurl(j), data: $(that).data(), key: i, index: i, value: value, row: value, suffix: suffix};
  341. var html = tpl ? Template(tpl, data) : Template.render(Upload.config.previewtpl, data);
  342. $("#" + preview_id).append(html);
  343. });
  344. refresh($("#" + preview_id).data("name"));
  345. });
  346. $("#" + input_id).trigger("change");
  347. }
  348. if (preview_id) {
  349. //监听文本框改变事件
  350. $("#" + preview_id).on('change keyup', "input,textarea,select", function () {
  351. refresh($(this).closest("ul").data("name"));
  352. });
  353. // 监听事件
  354. $(document.body).on("fa.preview.change", "#" + preview_id, function () {
  355. var urlArr = [];
  356. $("#" + preview_id + " [data-url]").each(function (i, j) {
  357. urlArr.push($(this).data("url"));
  358. });
  359. if (input_id) {
  360. $("#" + input_id).val(urlArr.join(","));
  361. }
  362. refresh($("#" + preview_id).data("name"));
  363. });
  364. // 移除按钮事件
  365. $(document.body).on("click", "#" + preview_id + " .btn-trash", function () {
  366. $(this).closest("li").remove();
  367. $("#" + preview_id).trigger("fa.preview.change");
  368. });
  369. }
  370. if (input_id) {
  371. //粘贴上传、拖拽上传
  372. $("body").on('paste drop', "#" + input_id, function (event) {
  373. var originEvent = event.originalEvent;
  374. var button = $(".plupload[data-input-id='" + $(this).attr("id") + "'],.faupload[data-input-id='" + $(this).attr("id") + "']");
  375. if (event.type === 'paste' && originEvent.clipboardData && originEvent.clipboardData.items) {
  376. var items = originEvent.clipboardData.items;
  377. if ((items.length === 1 && items[0].type.indexOf("text") > -1) || (items.length === 2 && items[1].type.indexOf("text") > -1)) {
  378. } else {
  379. Upload.list[button.attr("id")].paste(originEvent);
  380. return false;
  381. }
  382. }
  383. if (event.type === 'drop' && originEvent.dataTransfer && originEvent.dataTransfer.files) {
  384. Upload.list[button.attr("id")].drop(originEvent);
  385. return false;
  386. }
  387. });
  388. }
  389. });
  390. },
  391. /**
  392. * @deprecated Use upload instead.
  393. */
  394. plupload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
  395. return Upload.api.upload(element, onUploadSuccess, onUploadError, onUploadComplete);
  396. },
  397. /**
  398. * @deprecated Use upload instead.
  399. */
  400. faupload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
  401. return Upload.api.upload(element, onUploadSuccess, onUploadError, onUploadComplete);
  402. },
  403. // AJAX异步上传
  404. send: function (file, onUploadSuccess, onUploadError, onUploadComplete) {
  405. var index = Layer.msg(__('Uploading'), {offset: 't', time: 0});
  406. var id = "dropzone-" + Dropzone.uuidv4();
  407. $('<button type="button" id="' + id + '" class="btn btn-danger hidden faupload" />').appendTo("body");
  408. $("#" + id).data("upload-complete", function (files) {
  409. Layer.close(index);
  410. Upload.list[id].removeAllFiles(true);
  411. });
  412. Upload.api.upload("#" + id, onUploadSuccess, onUploadError, onUploadComplete);
  413. setTimeout(function () {
  414. Upload.list[id].addFile(file);
  415. }, 1);
  416. },
  417. custom: {
  418. //自定义上传完成回调
  419. afteruploadcallback: function (response) {
  420. console.log(this, response);
  421. alert("Custom Callback,Response URL:" + response.url);
  422. },
  423. }
  424. }
  425. }
  426. ;
  427. return Upload;
  428. });