editorAssetUpload.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /**
  2. * 富文本编辑器(@wangeditor/editor)素材库上传与「从素材库选择」公共封装。
  3. *
  4. * - buildEditorAssetMenuConf:生成 MENU_CONF.uploadImage / uploadVideo,
  5. * 上传端点统一指向 /api/admin/file-record/upload(fieldName=file,Bearer 认证),
  6. * 使编辑器内粘贴/拖拽/按钮上传自动写入 file_record(素材库)。
  7. * customInsert 用 resolveAssetUrl 规整 URL,修复旧代码 baseURL+url 在京东云
  8. * 绝对地址下产生的双前缀 bug。
  9. * - insertAssetIntoEditor:把素材库选中的记录插入编辑器光标处(图片/视频节点)。
  10. */
  11. import { Message } from 'element-ui'
  12. import { Boot } from '@wangeditor/editor'
  13. import { resolveAssetUrl } from './asset'
  14. const BASE_URL = process.env.VUE_APP_BASE_API || ''
  15. export function getUploadHeaders() {
  16. const token = localStorage.getItem('token')
  17. return token ? { Authorization: 'Bearer ' + token } : {}
  18. }
  19. function makeCustomInsert() {
  20. return function customInsert(res, insertFn) {
  21. if (!res) return
  22. if (res.code !== 200) {
  23. Message.error((res.message || '上传失败') + '(素材未入库)')
  24. return
  25. }
  26. const data = res.data
  27. const url = data && data.url ? data.url : data
  28. if (!url) return
  29. insertFn(resolveAssetUrl(url))
  30. }
  31. }
  32. /**
  33. * 编辑器顶层 config.customAlert 工厂。
  34. *
  35. * <p>注意:wangEditor 从编辑器顶层 config.customAlert 读取(不是 MENU_CONF.uploadImage.customAlert),
  36. * 因此必须挂在 editorConfig 根节点上:
  37. * <pre>
  38. * editorConfig = {
  39. * customAlert: getEditorCustomAlert(),
  40. * MENU_CONF: buildEditorAssetMenuConf({ category: 'articles' })
  41. * }
  42. * </pre>
  43. */
  44. export function getEditorCustomAlert() {
  45. // 注意:wangEditor 从编辑器顶层 config.customAlert 读取(不是 MENU_CONF.uploadImage.customAlert)
  46. return function customAlert(msg, type) {
  47. Message({ message: msg, type: type || 'error' })
  48. }
  49. }
  50. function makeOnError(label, maxSizeMB) {
  51. return function onError(file) {
  52. const name = (file && file.name) || label
  53. Message.error(name + ' 上传失败,' + label + '不能超过 ' + maxSizeMB + 'MB')
  54. }
  55. }
  56. /**
  57. * 生成 wangEditor MENU_CONF 的 uploadImage / uploadVideo 配置。
  58. *
  59. * @param {Object} opts
  60. * @param {String} opts.category 上传入库的素材分类,默认 general
  61. * @param {Number} opts.maxImageSize 图片上限(MB),默认 5
  62. * @param {Number} opts.maxVideoSize 视频上限(MB),默认 50
  63. * @returns {{uploadImage:Object, uploadVideo:Object}}
  64. */
  65. export function buildEditorAssetMenuConf(opts = {}) {
  66. const category = opts.category || 'general'
  67. const maxImageSize = opts.maxImageSize || 5
  68. const maxVideoSize = opts.maxVideoSize || 50
  69. return {
  70. uploadImage: {
  71. server: BASE_URL + '/api/admin/file-record/upload',
  72. headers: getUploadHeaders(),
  73. meta: { category },
  74. maxNumberOfFiles: 1,
  75. maxFileSize: maxImageSize * 1024 * 1024,
  76. fieldName: 'file',
  77. customInsert: makeCustomInsert(),
  78. onError: makeOnError('图片', maxImageSize)
  79. },
  80. uploadVideo: {
  81. server: BASE_URL + '/api/admin/file-record/upload',
  82. headers: getUploadHeaders(),
  83. meta: { category },
  84. maxNumberOfFiles: 1,
  85. maxFileSize: maxVideoSize * 1024 * 1024,
  86. fieldName: 'file',
  87. timeout: 5 * 60 * 1000,
  88. allowedFileTypes: ['video/*'],
  89. customInsert: makeCustomInsert(),
  90. onError: makeOnError('视频', maxVideoSize)
  91. }
  92. }
  93. }
  94. /**
  95. * 把素材库选中的记录插入编辑器当前光标处。
  96. *
  97. * @param {Object} editor wangEditor 实例
  98. * @param {Object} record 素材库记录(含 url/fileType)
  99. * @param {String} type image | video(不传时按 record.fileType 推断)
  100. */
  101. export function insertAssetIntoEditor(editor, record, type) {
  102. if (!editor || !record) return
  103. const url = resolveAssetUrl(record.url)
  104. if (!url) return
  105. const resolvedType = type || (record.fileType === 'video' ? 'video' : 'image')
  106. try {
  107. if (resolvedType === 'video') {
  108. editor.insertNode({
  109. type: 'video',
  110. src: url,
  111. poster: '',
  112. width: 'auto',
  113. height: 'auto',
  114. children: [{ text: '' }]
  115. })
  116. } else {
  117. editor.insertNode({
  118. type: 'image',
  119. src: url,
  120. alt: '',
  121. href: '',
  122. style: {},
  123. children: [{ text: '' }]
  124. })
  125. }
  126. } catch (e) {
  127. console.error('编辑器插入素材失败', e)
  128. try {
  129. editor.dangerouslyInsertHtml(
  130. resolvedType === 'video' ? '<video src="' + url + '"></video>' : '<img src="' + url + '"/>'
  131. )
  132. } catch (e2) {
  133. console.error('编辑器 HTML 兜底插入失败', e2)
  134. }
  135. }
  136. }
  137. // ==================== 编辑器工具栏「素材库」菜单 ====================
  138. export const ASSET_MENU_KEY = 'assetLibrary'
  139. let assetMenuHandler = null
  140. let assetMenuRegistered = false
  141. /**
  142. * 注册「素材库」按钮点击回调。页面在 created 时绑定,exec 时调用。
  143. * @param {Function} fn
  144. */
  145. export function setAssetMenuHandler(fn) {
  146. assetMenuHandler = typeof fn === 'function' ? fn : null
  147. }
  148. /**
  149. * 向 wangEditor 注册自定义「素材库」工具栏菜单(全局只注册一次)。
  150. * 必须在编辑器渲染前调用(页面 created 即可)。
  151. */
  152. export function registerAssetLibraryMenu() {
  153. if (assetMenuRegistered) return
  154. assetMenuRegistered = true
  155. Boot.registerMenu({
  156. key: ASSET_MENU_KEY,
  157. factory() {
  158. return {
  159. tag: 'button',
  160. title: '素材库',
  161. iconSvg: '<svg viewBox="0 0 1024 1024" width="16" height="16"><path fill="currentColor" d="M160 192h704a64 64 0 0 1 64 64v512a64 64 0 0 1-64 64H160a64 64 0 0 1-64-64V256a64 64 0 0 1 64-64zm0 64v512h704V256H160zm96 96h160a32 32 0 0 1 32 32v96a32 32 0 0 1-32 32H256a32 32 0 0 1-32-32v-96a32 32 0 0 1 32-32zm0 224h512v48H256v-48z"/></svg>',
  162. getValue() { return '' },
  163. isActive() { return false },
  164. isDisabled() { return false },
  165. exec() {
  166. if (assetMenuHandler) assetMenuHandler()
  167. }
  168. }
  169. }
  170. })
  171. }
  172. /**
  173. * 生成带「素材库」按钮的工具栏配置。
  174. * @param {Object} extra 额外 toolbarConfig 字段
  175. */
  176. export function buildAssetToolbarConfig(extra) {
  177. return Object.assign(
  178. { insertKeys: { index: 0, keys: [ASSET_MENU_KEY] } },
  179. extra || {}
  180. )
  181. }
  182. export default {
  183. buildEditorAssetMenuConf,
  184. insertAssetIntoEditor,
  185. getEditorCustomAlert,
  186. getUploadHeaders,
  187. registerAssetLibraryMenu,
  188. setAssetMenuHandler,
  189. buildAssetToolbarConfig,
  190. ASSET_MENU_KEY
  191. }