OssUpload.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. (function (global) {
  2. var ossUpload = {
  3. accessid: '',
  4. host: "",
  5. expire: 0,
  6. uploader: null,
  7. data: {},
  8. files: [],
  9. key: '',
  10. };
  11. /**
  12. * 初始化
  13. */
  14. ossUpload.init = function () {
  15. }
  16. /**
  17. * 获取配置签名
  18. * @returns {Promise<any>}
  19. */
  20. ossUpload.getSignature = function () {
  21. var that = this;
  22. return new Promise(function (resolve, reject) {
  23. var now = timestamp = Date.parse(new Date()) / 1000;
  24. if (that.expire > now + 3) {
  25. return resolve(that.data);
  26. }
  27. requestGet(getUrl({c: "widget.images", a: 'get_signature'})).then(function (res) {
  28. that.accessid = res.data.accessid;
  29. that.host = res.data.host;
  30. that.expire = parseInt(res.data.expire);
  31. that.data = res.data;
  32. resolve(res.data);
  33. }).catch(function (res) {
  34. reject(res);
  35. })
  36. })
  37. }
  38. /**
  39. * 获取key
  40. * @param len
  41. * @returns {string}
  42. */
  43. ossUpload.randomString = function (len) {
  44. len = len || 32;
  45. var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  46. var maxPos = chars.length;
  47. var pwd = '';
  48. for (i = 0; i < len; i++) {
  49. pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  50. }
  51. return pwd;
  52. }
  53. /**
  54. * 设置上传参数
  55. * @param up
  56. */
  57. ossUpload.setUploadParam = function (up, fileName) {
  58. var that = this;
  59. this.getSignature().then(function (res) {
  60. that.key = that.randomString(18) + that.getSuffix(fileName);
  61. up.setOption({
  62. url: that.host,
  63. multipart_params: {
  64. key: that.key,
  65. policy: res.policy,
  66. OSSAccessKeyId: res.accessid,
  67. success_action_status: "200",
  68. callback: res.callback,
  69. signature: res.signature,
  70. }
  71. });
  72. up.start();
  73. }).catch(function (res) {
  74. console.log(res);
  75. })
  76. }
  77. /**
  78. *
  79. * @param filename
  80. * @returns {string}
  81. */
  82. ossUpload.getSuffix = function (filename) {
  83. var pos = filename.lastIndexOf('.'), suffix = ''
  84. if (pos != -1) {
  85. suffix = filename.substring(pos)
  86. }
  87. return suffix;
  88. }
  89. /**
  90. * 上传文件
  91. * @param opt
  92. */
  93. ossUpload.upload = function (opt) {
  94. var that = this;
  95. if (typeof opt !== 'object') {
  96. opt = {};
  97. }
  98. var config = {
  99. idName: opt.id,
  100. mime_types: [
  101. {title: "Image files", extensions: "jpg,gif,png,bmp"},
  102. {title: "Mp4 files", extensions: "mp4"},
  103. {title: "Mp3 files", extensions: "mp3,wma"}
  104. ],
  105. max_file_size: '1000mb',
  106. prevent_duplicates: true,
  107. multi_selection: false,
  108. init: function (uploader) {
  109. },
  110. FilesAddedSuccess: function (files) {
  111. },
  112. uploadIng: function (file) {
  113. },
  114. success: function (res) {
  115. },
  116. fail: function (err) {
  117. }
  118. };
  119. Object.assign(config, opt);
  120. that.uploader = new plupload.Uploader({
  121. runtimes: 'html5,flash,silverlight,html4',
  122. browse_button: config.idName,
  123. multi_selection: config.multi_selection,
  124. flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
  125. silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
  126. url: 'http://oss.aliyuncs.com',
  127. filters: {
  128. mime_types: config.mime_types,
  129. max_file_size: config.max_file_size, //最大只能上传10mb的文件
  130. prevent_duplicates: config.prevent_duplicates //不允许选取重复文件
  131. },
  132. init: {
  133. PostInit: function () {
  134. config.init(that.uploader);
  135. },
  136. FilesAdded: function (up, files) {
  137. if (config.multi_selection === false) {
  138. that.setUploadParam(up, files[0].name);
  139. }
  140. config.FilesAddedSuccess(files);
  141. that.files = files;
  142. },
  143. BeforeUpload: function (up, file) {
  144. },
  145. UploadProgress: function (up, file) {
  146. config.uploadIng(file);
  147. },
  148. FileUploaded: function (up, file, info) {
  149. var key = that.key;
  150. that.key = '';
  151. if (info.status == 200) {
  152. config.success({key: key, host: that.host, url: that.host + '/' + key})
  153. } else if (info.status == 203) {
  154. config.fail(info.response)
  155. } else {
  156. config.success({key: key, host: that.host, url: that.host + '/' + key})
  157. }
  158. that.files = [];
  159. },
  160. Error: function (up, err) {
  161. if (err.code == -600) {
  162. config.fail('选择的文件太大了');
  163. } else if (err.code == -601) {
  164. config.fail('选择的文件后缀不对');
  165. } else if (err.code == -602) {
  166. config.fail('这个文件已经上传过一遍了');
  167. } else {
  168. config.fail(err.response);
  169. }
  170. }
  171. }
  172. });
  173. that.uploader.init();
  174. return that.uploader;
  175. }
  176. /**
  177. * 手动上传文件
  178. */
  179. ossUpload.start = function () {
  180. var that = this;
  181. that.files.map(function (file) {
  182. that.setUploadParam(that.uploader, file.name);
  183. })
  184. }
  185. /**
  186. * 获取图片html
  187. * @param $name
  188. * @param inputname
  189. * @returns {string}
  190. */
  191. ossUpload.getImageHtml = function ($name, inputname, host) {
  192. var host = (host !== undefined ? host : this.host + '/') + $name, inputname = inputname || 'image';
  193. return '<div class="upload-image-box">\n' +
  194. ' <img src="' + host + '" alt="">\n' +
  195. ' <input type="hidden" name="' + inputname + '" value="' + host + '">\n' +
  196. ' <div class="mask">\n' +
  197. ' <p><i class="fa fa-eye open_image" data-url="' + host + '"></i><i class="fa fa-trash-o delete_image" data-url="' + $name + '"></i></p>\n' +
  198. ' </div>\n' +
  199. '</div>';
  200. }
  201. /**
  202. * 绑定事件
  203. * @constructor
  204. */
  205. ossUpload.LoadEvent = function () {
  206. $('.upload-image-box').on({
  207. mouseover: function () {
  208. $(this).find('.mask').show();
  209. },
  210. mouseout: function () {
  211. $(this).find('.mask').hide();
  212. }
  213. })
  214. $('.open_image').on('click', function () {
  215. $eb.openImage($(this).data('url'));
  216. });
  217. }
  218. /**
  219. * 删除指定资源
  220. * @param key
  221. * @returns {Promise<any>}
  222. */
  223. ossUpload.delete = function (key, url) {
  224. return new Promise(function (resolve, reject) {
  225. requestGet(getUrl({
  226. c: "widget.images",
  227. a: 'del_oss_key',
  228. q: {key: key, url: url ? url : ''}
  229. })).then(function (res) {
  230. resolve(res);
  231. }).cache(function (res) {
  232. reject(res);
  233. })
  234. });
  235. }
  236. /**
  237. * 打开一个窗口
  238. * @param title
  239. * @param src
  240. * @param opt
  241. * @returns {*}
  242. */
  243. ossUpload.createFrame = function (title, p, opt) {
  244. opt === undefined && (opt = {});
  245. var h = 0;
  246. if (window.innerHeight < 800 && window.innerHeight >= 700) {
  247. h = window.innerHeight - 50;
  248. } else if (window.innerHeight < 900 && window.innerHeight >= 800) {
  249. h = window.innerHeight - 100;
  250. } else if (window.innerHeight < 1000 && window.innerHeight >= 900) {
  251. h = window.innerHeight - 150;
  252. } else if (window.innerHeight >= 1000) {
  253. h = window.innerHeight - 200;
  254. } else {
  255. h = window.innerHeight;
  256. }
  257. var src = getUrl({c: 'widget.images', a: 'index', q: p || {}});
  258. var area = [(opt.w || window.innerWidth / 2) + 'px', (!opt.h || opt.h > h ? h : opt.h) + 'px'];
  259. return layer.open({
  260. type: 2,
  261. title: title,
  262. area: area,
  263. fixed: false, //不固定
  264. maxmin: true,
  265. moveOut: false,//true 可以拖出窗外 false 只能在窗内拖
  266. anim: 5,//出场动画 isOutAnim bool 关闭动画
  267. offset: 'auto',//['100px','100px'],//'auto',//初始位置 ['100px','100px'] t[ 上 左]
  268. shade: 0,//遮罩
  269. resize: true,//是否允许拉伸
  270. content: src,//内容
  271. move: '.layui-layer-title'
  272. });
  273. }
  274. ossUpload.init();
  275. global.ossUpload = ossUpload;
  276. return ossUpload;
  277. }(this));