attachment.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /**
  2. * User: Jinqn
  3. * Date: 14-04-08
  4. * Time: 下午16:34
  5. * 上传图片对话框逻辑代码,包括tab: 远程图片/上传图片/在线图片/搜索图片
  6. */
  7. ;(function () {
  8. var uploadFile, onlineFile
  9. window.onload = function () {
  10. initTabs()
  11. initButtons()
  12. }
  13. /* 初始化tab标签 */
  14. function initTabs() {
  15. var tabs = $G('tabhead').children
  16. for (var i = 0; i < tabs.length; i++) {
  17. domUtils.on(tabs[i], 'click', function (e) {
  18. var target = e.target || e.srcElement
  19. setTabFocus(target.getAttribute('data-content-id'))
  20. })
  21. }
  22. setTabFocus('upload')
  23. }
  24. /* 初始化tabbody */
  25. function setTabFocus(id) {
  26. if (!id) return
  27. var i,
  28. bodyId,
  29. tabs = $G('tabhead').children
  30. for (i = 0; i < tabs.length; i++) {
  31. bodyId = tabs[i].getAttribute('data-content-id')
  32. if (bodyId == id) {
  33. domUtils.addClass(tabs[i], 'focus')
  34. domUtils.addClass($G(bodyId), 'focus')
  35. } else {
  36. domUtils.removeClasses(tabs[i], 'focus')
  37. domUtils.removeClasses($G(bodyId), 'focus')
  38. }
  39. }
  40. switch (id) {
  41. case 'upload':
  42. uploadFile = uploadFile || new UploadFile('queueList')
  43. break
  44. case 'online':
  45. onlineFile = onlineFile || new OnlineFile('fileList')
  46. break
  47. }
  48. }
  49. /* 初始化onok事件 */
  50. function initButtons() {
  51. dialog.onok = function () {
  52. var list = [],
  53. id,
  54. tabs = $G('tabhead').children
  55. for (var i = 0; i < tabs.length; i++) {
  56. if (domUtils.hasClass(tabs[i], 'focus')) {
  57. id = tabs[i].getAttribute('data-content-id')
  58. break
  59. }
  60. }
  61. switch (id) {
  62. case 'upload':
  63. list = uploadFile.getInsertList()
  64. var count = uploadFile.getQueueCount()
  65. if (count) {
  66. $('.info', '#queueList').html(
  67. '<span style="color:red;">' +
  68. '还有2个未上传文件'.replace(/[\d]/, count) +
  69. '</span>'
  70. )
  71. return false
  72. }
  73. break
  74. case 'online':
  75. list = onlineFile.getInsertList()
  76. break
  77. }
  78. editor.execCommand('insertfile', list)
  79. }
  80. }
  81. /* 上传附件 */
  82. function UploadFile(target) {
  83. this.$wrap = target.constructor == String ? $('#' + target) : $(target)
  84. this.init()
  85. }
  86. UploadFile.prototype = {
  87. init: function () {
  88. this.fileList = []
  89. this.initContainer()
  90. this.initUploader()
  91. },
  92. initContainer: function () {
  93. this.$queue = this.$wrap.find('.filelist')
  94. },
  95. /* 初始化容器 */
  96. initUploader: function () {
  97. var _this = this,
  98. $ = jQuery, // just in case. Make sure it's not an other libaray.
  99. $wrap = _this.$wrap,
  100. // 图片容器
  101. $queue = $wrap.find('.filelist'),
  102. // 状态栏,包括进度和控制按钮
  103. $statusBar = $wrap.find('.statusBar'),
  104. // 文件总体选择信息。
  105. $info = $statusBar.find('.info'),
  106. // 上传按钮
  107. $upload = $wrap.find('.uploadBtn'),
  108. // 上传按钮
  109. $filePickerBtn = $wrap.find('.filePickerBtn'),
  110. // 上传按钮
  111. $filePickerBlock = $wrap.find('.filePickerBlock'),
  112. // 没选择文件之前的内容。
  113. $placeHolder = $wrap.find('.placeholder'),
  114. // 总体进度条
  115. $progress = $statusBar.find('.progress').hide(),
  116. // 添加的文件数量
  117. fileCount = 0,
  118. // 添加的文件总大小
  119. fileSize = 0,
  120. // 优化retina, 在retina下这个值是2
  121. ratio = window.devicePixelRatio || 1,
  122. // 缩略图大小
  123. thumbnailWidth = 113 * ratio,
  124. thumbnailHeight = 113 * ratio,
  125. // 可能有pedding, ready, uploading, confirm, done.
  126. state = '',
  127. // 所有文件的进度信息,key为file id
  128. percentages = {},
  129. supportTransition = (function () {
  130. var s = document.createElement('p').style,
  131. r =
  132. 'transition' in s ||
  133. 'WebkitTransition' in s ||
  134. 'MozTransition' in s ||
  135. 'msTransition' in s ||
  136. 'OTransition' in s
  137. s = null
  138. return r
  139. })(),
  140. // WebUploader实例
  141. uploader,
  142. actionUrl = editor.getActionUrl(editor.getOpt('fileActionName')),
  143. fileMaxSize = editor.getOpt('fileMaxSize'),
  144. acceptExtensions = (editor.getOpt('fileAllowFiles') || [])
  145. .join('')
  146. .replace(/\./g, ',')
  147. .replace(/^[,]/, '')
  148. if (!WebUploader.Uploader.support()) {
  149. $('#filePickerReady')
  150. .after($('<div>').html(lang.errorNotSupport))
  151. .hide()
  152. return
  153. } else if (!editor.getOpt('fileActionName')) {
  154. $('#filePickerReady')
  155. .after($('<div>').html(lang.errorLoadConfig))
  156. .hide()
  157. return
  158. }
  159. uploader = _this.uploader = WebUploader.create({
  160. pick: {
  161. id: '#filePickerReady',
  162. label: lang.uploadSelectFile,
  163. },
  164. swf: '../../third-party/webuploader/Uploader.swf',
  165. server: actionUrl,
  166. fileVal: editor.getOpt('fileFieldName'),
  167. duplicate: true,
  168. fileSingleSizeLimit: fileMaxSize,
  169. compress: false,
  170. })
  171. uploader.addButton({
  172. id: '#filePickerBlock',
  173. })
  174. uploader.addButton({
  175. id: '#filePickerBtn',
  176. label: lang.uploadAddFile,
  177. })
  178. setState('pedding')
  179. // 当有文件添加进来时执行,负责view的创建
  180. function addFile(file) {
  181. var $li = $(
  182. '<li id="' +
  183. file.id +
  184. '">' +
  185. '<p class="title">' +
  186. file.name +
  187. '</p>' +
  188. '<p class="imgWrap"></p>' +
  189. '<p class="progress"><span></span></p>' +
  190. '</li>'
  191. ),
  192. $btns = $(
  193. '<div class="file-panel">' +
  194. '<span class="cancel">' +
  195. lang.uploadDelete +
  196. '</span>' +
  197. '<span class="rotateRight">' +
  198. lang.uploadTurnRight +
  199. '</span>' +
  200. '<span class="rotateLeft">' +
  201. lang.uploadTurnLeft +
  202. '</span></div>'
  203. ).appendTo($li),
  204. $prgress = $li.find('p.progress span'),
  205. $wrap = $li.find('p.imgWrap'),
  206. $info = $('<p class="error"></p>').hide().appendTo($li),
  207. showError = function (code) {
  208. switch (code) {
  209. case 'exceed_size':
  210. text = lang.errorExceedSize
  211. break
  212. case 'interrupt':
  213. text = lang.errorInterrupt
  214. break
  215. case 'http':
  216. text = lang.errorHttp
  217. break
  218. case 'not_allow_type':
  219. text = lang.errorFileType
  220. break
  221. default:
  222. text = lang.errorUploadRetry
  223. break
  224. }
  225. $info.text(text).show()
  226. }
  227. if (file.getStatus() === 'invalid') {
  228. showError(file.statusText)
  229. } else {
  230. $wrap.text(lang.uploadPreview)
  231. if (
  232. '|png|jpg|jpeg|bmp|gif|'.indexOf(
  233. '|' + file.ext.toLowerCase() + '|'
  234. ) == -1
  235. ) {
  236. $wrap
  237. .empty()
  238. .addClass('notimage')
  239. .append(
  240. '<i class="file-preview file-type-' +
  241. file.ext.toLowerCase() +
  242. '"></i>' +
  243. '<span class="file-title" title="' +
  244. file.name +
  245. '">' +
  246. file.name +
  247. '</span>'
  248. )
  249. } else {
  250. if (browser.ie && browser.version <= 7) {
  251. $wrap.text(lang.uploadNoPreview)
  252. } else {
  253. uploader.makeThumb(
  254. file,
  255. function (error, src) {
  256. if (error || !src) {
  257. $wrap.text(lang.uploadNoPreview)
  258. } else {
  259. var $img = $('<img src="' + src + '">')
  260. $wrap.empty().append($img)
  261. $img.on('error', function () {
  262. $wrap.text(lang.uploadNoPreview)
  263. })
  264. }
  265. },
  266. thumbnailWidth,
  267. thumbnailHeight
  268. )
  269. }
  270. }
  271. percentages[file.id] = [file.size, 0]
  272. file.rotation = 0
  273. /* 检查文件格式 */
  274. if (
  275. !file.ext ||
  276. acceptExtensions.indexOf(file.ext.toLowerCase()) == -1
  277. ) {
  278. showError('not_allow_type')
  279. uploader.removeFile(file)
  280. }
  281. }
  282. file.on('statuschange', function (cur, prev) {
  283. if (prev === 'progress') {
  284. $prgress.hide().width(0)
  285. } else if (prev === 'queued') {
  286. $li.off('mouseenter mouseleave')
  287. $btns.remove()
  288. }
  289. // 成功
  290. if (cur === 'error' || cur === 'invalid') {
  291. showError(file.statusText)
  292. percentages[file.id][1] = 1
  293. } else if (cur === 'interrupt') {
  294. showError('interrupt')
  295. } else if (cur === 'queued') {
  296. percentages[file.id][1] = 0
  297. } else if (cur === 'progress') {
  298. $info.hide()
  299. $prgress.css('display', 'block')
  300. } else if (cur === 'complete') {
  301. }
  302. $li.removeClass('state-' + prev).addClass('state-' + cur)
  303. })
  304. $li.on('mouseenter', function () {
  305. $btns.stop().animate({ height: 30 })
  306. })
  307. $li.on('mouseleave', function () {
  308. $btns.stop().animate({ height: 0 })
  309. })
  310. $btns.on('click', 'span', function () {
  311. var index = $(this).index(),
  312. deg
  313. switch (index) {
  314. case 0:
  315. uploader.removeFile(file)
  316. return
  317. case 1:
  318. file.rotation += 90
  319. break
  320. case 2:
  321. file.rotation -= 90
  322. break
  323. }
  324. if (supportTransition) {
  325. deg = 'rotate(' + file.rotation + 'deg)'
  326. $wrap.css({
  327. '-webkit-transform': deg,
  328. '-mos-transform': deg,
  329. '-o-transform': deg,
  330. transform: deg,
  331. })
  332. } else {
  333. $wrap.css(
  334. 'filter',
  335. 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' +
  336. (~~(((file.rotation / 90) % 4) + 4) % 4) +
  337. ')'
  338. )
  339. }
  340. })
  341. $li.insertBefore($filePickerBlock)
  342. }
  343. // 负责view的销毁
  344. function removeFile(file) {
  345. var $li = $('#' + file.id)
  346. delete percentages[file.id]
  347. updateTotalProgress()
  348. $li.off().find('.file-panel').off().end().remove()
  349. }
  350. function updateTotalProgress() {
  351. var loaded = 0,
  352. total = 0,
  353. spans = $progress.children(),
  354. percent
  355. $.each(percentages, function (k, v) {
  356. total += v[0]
  357. loaded += v[0] * v[1]
  358. })
  359. percent = total ? loaded / total : 0
  360. spans.eq(0).text(Math.round(percent * 100) + '%')
  361. spans.eq(1).css('width', Math.round(percent * 100) + '%')
  362. updateStatus()
  363. }
  364. function setState(val, files) {
  365. if (val != state) {
  366. var stats = uploader.getStats()
  367. $upload.removeClass('state-' + state)
  368. $upload.addClass('state-' + val)
  369. switch (val) {
  370. /* 未选择文件 */
  371. case 'pedding':
  372. $queue.addClass('element-invisible')
  373. $statusBar.addClass('element-invisible')
  374. $placeHolder.removeClass('element-invisible')
  375. $progress.hide()
  376. $info.hide()
  377. uploader.refresh()
  378. break
  379. /* 可以开始上传 */
  380. case 'ready':
  381. $placeHolder.addClass('element-invisible')
  382. $queue.removeClass('element-invisible')
  383. $statusBar.removeClass('element-invisible')
  384. $progress.hide()
  385. $info.show()
  386. $upload.text(lang.uploadStart)
  387. uploader.refresh()
  388. break
  389. /* 上传中 */
  390. case 'uploading':
  391. $progress.show()
  392. $info.hide()
  393. $upload.text(lang.uploadPause)
  394. break
  395. /* 暂停上传 */
  396. case 'paused':
  397. $progress.show()
  398. $info.hide()
  399. $upload.text(lang.uploadContinue)
  400. break
  401. case 'confirm':
  402. $progress.show()
  403. $info.hide()
  404. $upload.text(lang.uploadStart)
  405. stats = uploader.getStats()
  406. if (stats.successNum && !stats.uploadFailNum) {
  407. setState('finish')
  408. return
  409. }
  410. break
  411. case 'finish':
  412. $progress.hide()
  413. $info.show()
  414. if (stats.uploadFailNum) {
  415. $upload.text(lang.uploadRetry)
  416. } else {
  417. $upload.text(lang.uploadStart)
  418. }
  419. break
  420. }
  421. state = val
  422. updateStatus()
  423. }
  424. if (!_this.getQueueCount()) {
  425. $upload.addClass('disabled')
  426. } else {
  427. $upload.removeClass('disabled')
  428. }
  429. }
  430. function updateStatus() {
  431. var text = '',
  432. stats
  433. if (state === 'ready') {
  434. text = lang.updateStatusReady
  435. .replace('_', fileCount)
  436. .replace('_KB', WebUploader.formatSize(fileSize))
  437. } else if (state === 'confirm') {
  438. stats = uploader.getStats()
  439. if (stats.uploadFailNum) {
  440. text = lang.updateStatusConfirm
  441. .replace('_', stats.successNum)
  442. .replace('_', stats.successNum)
  443. }
  444. } else {
  445. stats = uploader.getStats()
  446. text = lang.updateStatusFinish
  447. .replace('_', fileCount)
  448. .replace('_KB', WebUploader.formatSize(fileSize))
  449. .replace('_', stats.successNum)
  450. if (stats.uploadFailNum) {
  451. text += lang.updateStatusError.replace('_', stats.uploadFailNum)
  452. }
  453. }
  454. $info.html(text)
  455. }
  456. uploader.on('fileQueued', function (file) {
  457. fileCount++
  458. fileSize += file.size
  459. if (fileCount === 1) {
  460. $placeHolder.addClass('element-invisible')
  461. $statusBar.show()
  462. }
  463. addFile(file)
  464. })
  465. uploader.on('fileDequeued', function (file) {
  466. fileCount--
  467. fileSize -= file.size
  468. removeFile(file)
  469. updateTotalProgress()
  470. })
  471. uploader.on('filesQueued', function (file) {
  472. if (
  473. !uploader.isInProgress() &&
  474. (state == 'pedding' ||
  475. state == 'finish' ||
  476. state == 'confirm' ||
  477. state == 'ready')
  478. ) {
  479. setState('ready')
  480. }
  481. updateTotalProgress()
  482. })
  483. uploader.on('all', function (type, files) {
  484. switch (type) {
  485. case 'uploadFinished':
  486. setState('confirm', files)
  487. break
  488. case 'startUpload':
  489. /* 添加额外的GET参数 */
  490. var params =
  491. utils.serializeParam(editor.queryCommandValue('serverparam')) ||
  492. '',
  493. url = utils.formatUrl(
  494. actionUrl +
  495. (actionUrl.indexOf('?') == -1 ? '?' : '&') +
  496. 'encode=utf-8&' +
  497. params
  498. )
  499. uploader.option('server', url)
  500. setState('uploading', files)
  501. break
  502. case 'stopUpload':
  503. setState('paused', files)
  504. break
  505. }
  506. })
  507. uploader.on('uploadBeforeSend', function (file, data, header) {
  508. //这里可以通过data对象添加POST参数
  509. header['X_Requested_With'] = 'XMLHttpRequest'
  510. // HaoChuan9421
  511. if (
  512. editor.options.headers &&
  513. Object.prototype.toString.apply(editor.options.headers) ===
  514. '[object Object]'
  515. ) {
  516. for (var key in editor.options.headers) {
  517. header[key] = editor.options.headers[key]
  518. }
  519. }
  520. })
  521. uploader.on('uploadProgress', function (file, percentage) {
  522. var $li = $('#' + file.id),
  523. $percent = $li.find('.progress span')
  524. $percent.css('width', percentage * 100 + '%')
  525. percentages[file.id][1] = percentage
  526. updateTotalProgress()
  527. })
  528. uploader.on('uploadSuccess', function (file, ret) {
  529. var $file = $('#' + file.id)
  530. try {
  531. var responseText = ret._raw || ret,
  532. json = utils.str2json(responseText)
  533. if (json.state == 'SUCCESS') {
  534. _this.fileList.push(json)
  535. $file.append('<span class="success"></span>')
  536. } else {
  537. $file.find('.error').text(json.state).show()
  538. }
  539. } catch (e) {
  540. $file.find('.error').text(lang.errorServerUpload).show()
  541. }
  542. })
  543. uploader.on('uploadError', function (file, code) {})
  544. uploader.on('error', function (code, file) {
  545. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  546. addFile(file)
  547. }
  548. })
  549. uploader.on('uploadComplete', function (file, ret) {})
  550. $upload.on('click', function () {
  551. if ($(this).hasClass('disabled')) {
  552. return false
  553. }
  554. if (state === 'ready') {
  555. uploader.upload()
  556. } else if (state === 'paused') {
  557. uploader.upload()
  558. } else if (state === 'uploading') {
  559. uploader.stop()
  560. }
  561. })
  562. $upload.addClass('state-' + state)
  563. updateTotalProgress()
  564. },
  565. getQueueCount: function () {
  566. var file,
  567. i,
  568. status,
  569. readyFile = 0,
  570. files = this.uploader.getFiles()
  571. for (i = 0; (file = files[i++]); ) {
  572. status = file.getStatus()
  573. if (status == 'queued' || status == 'uploading' || status == 'progress')
  574. readyFile++
  575. }
  576. return readyFile
  577. },
  578. getInsertList: function () {
  579. var i,
  580. link,
  581. data,
  582. list = [],
  583. prefix = editor.getOpt('fileUrlPrefix')
  584. for (i = 0; i < this.fileList.length; i++) {
  585. data = this.fileList[i]
  586. link = data.url
  587. list.push({
  588. title: data.original || link.substr(link.lastIndexOf('/') + 1),
  589. url: prefix + link,
  590. })
  591. }
  592. return list
  593. },
  594. }
  595. /* 在线附件 */
  596. function OnlineFile(target) {
  597. this.container = utils.isString(target)
  598. ? document.getElementById(target)
  599. : target
  600. this.init()
  601. }
  602. OnlineFile.prototype = {
  603. init: function () {
  604. this.initContainer()
  605. this.initEvents()
  606. this.initData()
  607. },
  608. /* 初始化容器 */
  609. initContainer: function () {
  610. this.container.innerHTML = ''
  611. this.list = document.createElement('ul')
  612. this.clearFloat = document.createElement('li')
  613. domUtils.addClass(this.list, 'list')
  614. domUtils.addClass(this.clearFloat, 'clearFloat')
  615. this.list.appendChild(this.clearFloat)
  616. this.container.appendChild(this.list)
  617. },
  618. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  619. initEvents: function () {
  620. var _this = this
  621. /* 滚动拉取图片 */
  622. domUtils.on($G('fileList'), 'scroll', function (e) {
  623. var panel = this
  624. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  625. _this.getFileData()
  626. }
  627. })
  628. /* 选中图片 */
  629. domUtils.on(this.list, 'click', function (e) {
  630. var target = e.target || e.srcElement,
  631. li = target.parentNode
  632. if (li.tagName.toLowerCase() == 'li') {
  633. if (domUtils.hasClass(li, 'selected')) {
  634. domUtils.removeClasses(li, 'selected')
  635. } else {
  636. domUtils.addClass(li, 'selected')
  637. }
  638. }
  639. })
  640. },
  641. /* 初始化第一次的数据 */
  642. initData: function () {
  643. /* 拉取数据需要使用的值 */
  644. this.state = 0
  645. this.listSize = editor.getOpt('fileManagerListSize')
  646. this.listIndex = 0
  647. this.listEnd = false
  648. /* 第一次拉取数据 */
  649. this.getFileData()
  650. },
  651. /* 向后台拉取图片列表数据 */
  652. getFileData: function () {
  653. var _this = this
  654. if (!_this.listEnd && !this.isLoadingData) {
  655. this.isLoadingData = true
  656. ajax.request(
  657. editor.getActionUrl(editor.getOpt('fileManagerActionName')),
  658. {
  659. timeout: 100000,
  660. data: utils.extend(
  661. {
  662. start: this.listIndex,
  663. size: this.listSize,
  664. },
  665. editor.queryCommandValue('serverparam')
  666. ),
  667. method: 'get',
  668. onsuccess: function (r) {
  669. try {
  670. var json = eval('(' + r.responseText + ')')
  671. if (json.state == 'SUCCESS') {
  672. _this.pushData(json.list)
  673. _this.listIndex =
  674. parseInt(json.start) + parseInt(json.list.length)
  675. if (_this.listIndex >= json.total) {
  676. _this.listEnd = true
  677. }
  678. _this.isLoadingData = false
  679. }
  680. } catch (e) {
  681. if (r.responseText.indexOf('ue_separate_ue') != -1) {
  682. var list = r.responseText.split(r.responseText)
  683. _this.pushData(list)
  684. _this.listIndex = parseInt(list.length)
  685. _this.listEnd = true
  686. _this.isLoadingData = false
  687. }
  688. }
  689. },
  690. onerror: function () {
  691. _this.isLoadingData = false
  692. },
  693. }
  694. )
  695. }
  696. },
  697. /* 添加图片到列表界面上 */
  698. pushData: function (list) {
  699. var i,
  700. item,
  701. img,
  702. filetype,
  703. preview,
  704. icon,
  705. _this = this,
  706. urlPrefix = editor.getOpt('fileManagerUrlPrefix')
  707. for (i = 0; i < list.length; i++) {
  708. if (list[i] && list[i].url) {
  709. item = document.createElement('li')
  710. icon = document.createElement('span')
  711. filetype = list[i].url.substr(list[i].url.lastIndexOf('.') + 1)
  712. if ('png|jpg|jpeg|gif|bmp'.indexOf(filetype) != -1) {
  713. preview = document.createElement('img')
  714. domUtils.on(
  715. preview,
  716. 'load',
  717. (function (image) {
  718. return function () {
  719. _this.scale(
  720. image,
  721. image.parentNode.offsetWidth,
  722. image.parentNode.offsetHeight
  723. )
  724. }
  725. })(preview)
  726. )
  727. preview.width = 113
  728. preview.setAttribute(
  729. 'src',
  730. urlPrefix +
  731. list[i].url +
  732. (list[i].url.indexOf('?') == -1 ? '?noCache=' : '&noCache=') +
  733. (+new Date()).toString(36)
  734. )
  735. } else {
  736. var ic = document.createElement('i'),
  737. textSpan = document.createElement('span')
  738. textSpan.innerHTML = list[i].url.substr(
  739. list[i].url.lastIndexOf('/') + 1
  740. )
  741. preview = document.createElement('div')
  742. preview.appendChild(ic)
  743. preview.appendChild(textSpan)
  744. domUtils.addClass(preview, 'file-wrapper')
  745. domUtils.addClass(textSpan, 'file-title')
  746. domUtils.addClass(ic, 'file-type-' + filetype)
  747. domUtils.addClass(ic, 'file-preview')
  748. }
  749. domUtils.addClass(icon, 'icon')
  750. item.setAttribute('data-url', urlPrefix + list[i].url)
  751. if (list[i].original) {
  752. item.setAttribute('data-title', list[i].original)
  753. }
  754. item.appendChild(preview)
  755. item.appendChild(icon)
  756. this.list.insertBefore(item, this.clearFloat)
  757. }
  758. }
  759. },
  760. /* 改变图片大小 */
  761. scale: function (img, w, h, type) {
  762. var ow = img.width,
  763. oh = img.height
  764. if (type == 'justify') {
  765. if (ow >= oh) {
  766. img.width = w
  767. img.height = (h * oh) / ow
  768. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px'
  769. } else {
  770. img.width = (w * ow) / oh
  771. img.height = h
  772. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px'
  773. }
  774. } else {
  775. if (ow >= oh) {
  776. img.width = (w * ow) / oh
  777. img.height = h
  778. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px'
  779. } else {
  780. img.width = w
  781. img.height = (h * oh) / ow
  782. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px'
  783. }
  784. }
  785. },
  786. getInsertList: function () {
  787. var i,
  788. lis = this.list.children,
  789. list = []
  790. for (i = 0; i < lis.length; i++) {
  791. if (domUtils.hasClass(lis[i], 'selected')) {
  792. var url = lis[i].getAttribute('data-url')
  793. var title =
  794. lis[i].getAttribute('data-title') ||
  795. url.substr(url.lastIndexOf('/') + 1)
  796. list.push({
  797. title: title,
  798. url: url,
  799. })
  800. }
  801. }
  802. return list
  803. },
  804. }
  805. })()