如何使用Spring Boot集成百度UEditor实现图文及文件上传功能?

2026-04-28 11:572阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计3983个文字,预计阅读时间需要16分钟。

如何使用Spring Boot集成百度UEditor实现图文及文件上传功能?

Spring Boot 整合 UEditor 实现图片和文件上传功能,前端页面:

在阅读本篇教程之前,请先按照我的这篇随笔完成对 UEditor 的前期配置工作:Spring Boot + layui 整合百度富文本编辑器 UEditor 入门使用教程。

springboot整合ueditor实现图片上传和文件上传功能

写在前面:

在阅读本篇之前,请先按照我的这篇随笔完成对ueditor的前期配置工作:

springboot+layui 整合百度富文本编辑器ueditor入门使用教程(踩过的坑)www.cnblogs.com/rainbow-1/p/16365016.html

在完成对ueditor的基本配置后,图片和文件的上传主要是后端文件的配置,下面简单介绍一下步骤。


一、修改ueditor.config.js配置文件

首先第一步,要完成对配置文件的修改。默认的ueditor配置里,对配置文件的读取是通过controller.jsp完成的,

因为springboot项目中,静态jsp文件的访问是不被允许的,所以我们需要重写这段读取配置文件信息的代码,也就是通过写自己的一个controller来完成这个过程,同时自定义图片和文件上传的位置等信息。

默认的controller.jsp位置如下图:

这时候我们修改配置文件调用资源的接口名称,打开ueditor.config.js,如下图所示:

我通过server_url,拿到了项目的根路径,然后拼接后面的/science-2.0/api/ueditor/config(项目名称/路由名称)拿到完整的访问路径。

二、编写一个新的控制器(CommonController)

这个类就是我们第一步所修改的部分指向的这个控制器,它要完成对config.json文件(该文件位于jsp文件夹下,里面是关于文件上传的一些配置信息)的读取,同时要完成对文件上传的具体实现。

  • 下面我们先来看一下config.json文件(/jsp目录下)

​ 主要看一下图片上传配置的部分:

我们需要修改的部分如图所示:basePath指的是你希望保存的磁盘位置(这个目录最好事先存在),imageActionName是我们处理上传图片功能的那个路由,也就是在controller里是什么,这里就是什么。

下面的文件上传部分类似:

如何使用Spring Boot集成百度UEditor实现图文及文件上传功能?

  • 下面给出完成的controller代码

import com.alibaba.fastjson.JSONException; import com.baidu.ueditor.ActionEnter; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.ClassUtils; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.UUID; import javax.servlet.bs.baidu.com/listicon/'//自定义标号的路径 //,maxListLevel : 3 //限制可以tab的级数, 设置-1为不限制 //,autoTransWordToList:false //禁止word中粘贴进来的列表自动变成列表标签 //fontfamily //字体设置 label留空支持多语言自动切换,若配置,则以配置值为准 ,'fontfamily':[ { label:'',name:'songti',val:'宋体,SimSun'}, { label: '', name: 'SimSun', val: '仿宋,SimSun' }, { label:'',name:'FangSong_GB2312',val:'仿宋_GB2312 ,FangSong_GB2312'}, { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'}, { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'}, { label:'',name:'heiti',val:'黑体, SimHei'}, { label:'',name:'lishu',val:'隶书, SimLi'}, { label:'',name:'andaleMono',val:'andale mono'}, { label:'',name:'arial',val:'arial, helvetica,sans-serif'}, { label:'',name:'arialBlack',val:'arial black,avant garde'}, { label:'',name:'comicSansMs',val:'comic sans ms'}, { label:'',name:'impact',val:'impact,chicago'}, { label:'',name:'timesNewRoman',val:'times new roman'} ] //fontsize //字号 //,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36] //paragraph //段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准 //,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''} //rowspacingtop //段间距 值和显示的名字相同 //,'rowspacingtop':['5', '10', '15', '20', '25'] //rowspacingBottom //段间距 值和显示的名字相同 //,'rowspacingbottom':['5', '10', '15', '20', '25'] //lineheight //行内间距 值和显示的名字相同 //,'lineheight':['1', '1.5','1.75','2', '3', '4', '5'] //customstyle //自定义样式,不支持国际化,此处配置值即可最后显示值 //block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置 //尽量使用一些常用的标签 //参数说明 //tag 使用的标签名字 //label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同, //style 添加的样式 //每一个对象就是一个自定义的样式 //,'customstyle':[ // {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'}, // {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'}, // {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'}, // {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'} //] //打开右键菜单功能 //,enableContextMenu: true //右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准 //,contextMenu:[ // { // label:'', //显示的名称 // cmdName:'selectall',//执行的command命令,当点击这个右键菜单时 // //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName // exec:function () { // //this是当前编辑器的实例 // //this.ui._dialogs['inserttableDialog'].open(); // } // } //] //快捷菜单 //,shortcutMenu:["fontfamily", "fontsize", "bold", "italic", "underline", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist"] //elementPathEnabled //是否启用元素路径,默认是显示 //,elementPathEnabled : true //wordCount //,wordCount:true //是否开启字数统计 //,maximumWords:10000 //允许的最大字符数 //字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示 //,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符 //超出字数限制提示 留空支持多语言自动切换,否则按此配置显示 //,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span> //tab //点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位 //,tabSize:4 //,tabNode:'&nbsp;' //removeFormat //清除格式时可以删除的标签和属性 //removeForamtTags标签 //,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' //removeFormatAttributes属性 //,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign' //undo //可以最多回退的次数,默认20 //,maxUndoCount:20 //当输入的字符数超过该值时,保存一次现场 //,maxInputCount:1 //autoHeightEnabled // 是否自动长高,默认true //,autoHeightEnabled:true //scaleEnabled //是否可以拉伸长高,默认true(当开启时,自动长高失效) //,scaleEnabled:false //,minFrameWidth:800 //编辑器拖动时最小宽度,默认800 //,minFrameHeight:220 //编辑器拖动时最小高度,默认220 //autoFloatEnabled //是否保持toolbar的位置不动,默认true //,autoFloatEnabled:true //浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面 //,topOffset:30 //编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效) //,toolbarTopOffset:400 //设置远程图片是否抓取到本地保存 //,catchRemoteImageEnable: true //设置是否抓取远程图片 //pageBreakTag //分页标识符,默认是_ueditor_page_break_tag_ //,pageBreakTag:'_ueditor_page_break_tag_' //autotypeset //自动排版参数 //,autotypeset: { // mergeEmptyline: true, //合并空行 // removeClass: true, //去掉冗余的class // removeEmptyline: false, //去掉空行 // textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版 // imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版 // pasteFilter: false, //根据规则过滤没事粘贴进来的内容 // clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号 // clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体 // removeEmptyNode: false, // 去掉空节点 // //可以去掉的标签 // removeTagNames: {标签名字:1}, // indent: false, // 行首缩进 // indentValue : '2em', //行首缩进的大小 // bdc2sb: false, // tobdc: false //} //tableDragable //表格是否可以拖拽 //,tableDragable: true //sourceEditor //源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror //注意默认codemirror只能在ie8+和非ie中使用 //,sourceEditor:"codemirror" //如果sourceEditor是codemirror,还用配置一下两个参数 //codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js" //,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js" //codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css" //,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css" //编辑器初始化完成后是否进入源码模式,默认为否。 //,sourceEditorFirst:false //iframeUrlMap //dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径 //,iframeUrlMap:{ // 'anchor':'~/dialogs/anchor/anchor.html', //} //allowLinkProtocol 允许的链接地址,有这些前缀的链接地址不会自动添加app.baidu.com/static/cms/getapikey.html //, webAppKey: "" //默认过滤规则相关配置项目 //,disabledTableInTable:true //禁止表格嵌套 //,allowDivTransToP:true //允许进入编辑器的div标签自动变成p标签 //,rgb2Hex:true //默认产出的数据中的color自动从rgb格式变成16进制格式 // xss 过滤是否开启,inserthtml等操作 ,xssFilterRules: true //input xss过滤 ,inputXssFilter: true //output xss过滤 ,outputXssFilter: true // xss过滤白名单 名单来源: raw.githubusercontent.com/leizongmin/js-xss/master/lib/default.js ,whitList: { iframe: ['frameborder','border','marginwidth','marginheight','width','height','src','id'],//宋雨佳增加这一行 a: ['target', 'href', 'title', 'class', 'style'], abbr: ['title', 'class', 'style'], address: ['class', 'style'], area: ['shape', 'coords', 'href', 'alt'], article: [], aside: [], audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'], b: ['class', 'style'], bdi: ['dir'], bdo: ['dir'], big: [], blockquote: ['cite', 'class', 'style'], br: [], caption: ['class', 'style'], center: [], cite: [], code: ['class', 'style'], col: ['align', 'valign', 'span', 'width', 'class', 'style'], colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'], dd: ['class', 'style'], del: ['datetime'], details: ['open'], div: ['class', 'style'], dl: ['class', 'style'], dt: ['class', 'style'], em: ['class', 'style'], font: ['color', 'size', 'face'], footer: [], h1: ['class', 'style'], h2: ['class', 'style'], h3: ['class', 'style'], h4: ['class', 'style'], h5: ['class', 'style'], h6: ['class', 'style'], header: [], hr: [], i: ['class', 'style'], img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', 'loadingclass', 'class', 'data-latex'], ins: ['datetime'], li: ['class', 'style'], mark: [], nav: [], ol: ['class', 'style'], p: ['class', 'style'], pre: ['class', 'style'], s: [], section:[], small: [], span: ['class', 'style'], sub: ['class', 'style'], sup: ['class', 'style'], strong: ['class', 'style'], table: ['width', 'border', 'align', 'valign', 'class', 'style'], tbody: ['align', 'valign', 'class', 'style'], td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'], tfoot: ['align', 'valign', 'class', 'style'], th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'], thead: ['align', 'valign', 'class', 'style'], tr: ['rowspan', 'align', 'valign', 'class', 'style'], tt: [], u: [], ul: ['class', 'style'], video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style'] } }; function getUEBasePath(docUrl, confUrl) { return getBasePath(docUrl || self.document.URL || self.location.href, confUrl || getConfigFilePath()); } function getConfigFilePath() { var configPath = document.getElementsByTagName('script'); return configPath[ configPath.length - 1 ].src; } function getBasePath(docUrl, confUrl) { var basePath = confUrl; if (/^(\/|\\\\)/.test(confUrl)) { basePath = /^.+?\w(\/|\\\\)/.exec(docUrl)[0] + confUrl.replace(/^(\/|\\\\)/, ''); } else if (!/^[a-z]+:/i.test(confUrl)) { docUrl = docUrl.split("#")[0].split("?")[0].replace(/[^\\\/]+$/, ''); basePath = docUrl + "" + confUrl; } return optimizationPath(basePath); } function optimizationPath(path) { var protocol = /^[a-z]+:\/\//.exec(path)[ 0 ], tmp = null, res = []; path = path.replace(protocol, "").split("?")[0].split("#")[0]; path = path.replace(/\\/g, '/').split(/\//); path[ path.length - 1 ] = ""; while (path.length) { if (( tmp = path.shift() ) === "..") { res.pop(); } else if (tmp !== ".") { res.push(tmp); } } return protocol + res.join("/"); } window.UE = { getUEBasePath: getUEBasePath }; })(); 附config.json

/* 前后端通信相关的配置,注释只允许使用多行方式 */ { "basePath": "D:/scinece-2.0", /* 上传图片配置项 */ "imageActionName": "uploadimage", /* 执行上传图片的action名称 */ "imageFieldName": "upfile", /* 提交的图片表单名称 */ "imageMaxSize": 2048000, /* 上传大小限制,单位B */ "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */ "imageCompressEnable": true, /* 是否压缩图片,默认是true */ "imageCompressBorder": 1600, /* 图片压缩最长边限制 */ "imageInsertAlign": "none", /* 插入的图片浮动方式 */ "imageUrlPrefix":"", /* 图片访问路径前缀 */ "imagePathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */ /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */ /* {time} 会替换成时间戳 */ /* {yyyy} 会替换成四位年份 */ /* {yy} 会替换成两位年份 */ /* {mm} 会替换成两位月份 */ /* {dd} 会替换成两位日期 */ /* {hh} 会替换成两位小时 */ /* {ii} 会替换成两位分钟 */ /* {ss} 会替换成两位秒 */ /* 非法字符 \ : * ? " < > | */ /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */ /* 涂鸦图片上传配置项 */ "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */ "scrawlFieldName": "upfile", /* 提交的图片表单名称 */ "scrawlPathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */ "scrawlUrlPrefix":"", /* 图片访问路径前缀 */ "scrawlInsertAlign": "none", /* 截图工具上传 */ "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */ "snapscreenPathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "snapscreenUrlPrefix":"", /* 图片访问路径前缀 */ "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */ /* 抓取远程图片配置 */ "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"], "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */ "catcherFieldName": "source", /* 提交的图片列表表单名称 */ "catcherPathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "catcherUrlPrefix":"", /* 图片访问路径前缀 */ "catcherMaxSize": 2048000, /* 上传大小限制,单位B */ "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */ /* 上传视频配置 */ "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */ "videoFieldName": "upfile", /* 提交的视频表单名称 */ "videoPathFormat": "/document/ueditor/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "videoUrlPrefix": "", /* 视频访问路径前缀 */ "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */ "videoAllowFiles": [ ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */ /* 上传文件配置 */ "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */ "fileFieldName": "upfile", /* 提交的文件表单名称 */ "filePathFormat": "/document/ueditor/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "fileUrlPrefix":"", /* 文件访问路径前缀 */ "fileMaxSize": 307200000, /* 上传大小限制,单位B,默认50MB */ "fileAllowFiles": [ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" ], /* 上传文件格式显示 */ /* 列出指定目录下的图片 */ "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */ "imageManagerListPath": "/document/ueditor/image/", /* 指定要列出图片的目录 */ "imageManagerListSize": 20, /* 每次列出文件数量 */ "imageManagerUrlPrefix":"", /* 图片访问路径前缀 */ "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */ "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */ /* 列出指定目录下的文件 */ "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */ "fileManagerListPath": "/document/ueditor/file/", /* 指定要列出文件的目录 */ "fileManagerUrlPrefix":"", /* 文件访问路径前缀 */ "fileManagerListSize": 20, /* 每次列出文件数量 */ "fileManagerAllowFiles": [ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" ] /* 列出的文件类型 */ }

注意点 1 :如果你是按照我的上一篇随笔完成的对ueditor的初始配置,那么在你引入ueditor控件的那个html文件里,一定存在这么一段代码:

<script type="text/javascript"> window.UEDITOR_HOME_URL = "/UEditor/"; </script>

这次在ueditor.config.js文件中,我指定了这个路径,所以在页面里的这个声明就可以去掉了。而且我留着这里是存在问题的,当然我不太确定是不是这里导致的问题,如果大家配置完没有问题,那这里保留着也可以。

注意点 2 :这里面有几个路径需要再提醒一下

在CommonController中: @RequestMapping("uploadimage")和 @RequestMapping("uploadfile") 需要和 config.json中的imageActionName一一对应。

config.json中:"basePath": "D:/scinece-2.0" 需要是你保存在磁盘的路径,当然这里好像不改也行,因为这里被新写的controller覆盖了,可以尝试不改看看有没有问题,博主保险起见就一起改了。

CommonController 中的 map.put("url", "/PathFile/"+nowName);需要和映射器类的registry.addResourceHandler("/PathImage/**").addResourceLocations("file:/D:/science-2.0/"); 一一对应

CommonController 中的 rootPath = afterPath+ "static/UEditor/jsp";是相对于项目的classpath的路径

对于SpringBoot项目来说,classpath指的是src.main.java和src.main.resources路径以及第三方jar包的根路径,存放在这两个路径下的文件,都可以通过classpath作为相对路径来引用;

因为在maven项目打包之后,会将项目变成如下图所示的路径,也就是说 /java 和 /resources 这两个文件夹所在的路径会消失springboot项目会直接识别这两个文件夹里面的内容,****所以我们写路径的时候就直接可以从 resources 目录的下一级开始,比如从/static或者 /template等等开始。

分享完毕,有不准确的地方大家交流指正,希望对大家有帮助!

好看请赞,养成习惯!

本文共计3983个文字,预计阅读时间需要16分钟。

如何使用Spring Boot集成百度UEditor实现图文及文件上传功能?

Spring Boot 整合 UEditor 实现图片和文件上传功能,前端页面:

在阅读本篇教程之前,请先按照我的这篇随笔完成对 UEditor 的前期配置工作:Spring Boot + layui 整合百度富文本编辑器 UEditor 入门使用教程。

springboot整合ueditor实现图片上传和文件上传功能

写在前面:

在阅读本篇之前,请先按照我的这篇随笔完成对ueditor的前期配置工作:

springboot+layui 整合百度富文本编辑器ueditor入门使用教程(踩过的坑)www.cnblogs.com/rainbow-1/p/16365016.html

在完成对ueditor的基本配置后,图片和文件的上传主要是后端文件的配置,下面简单介绍一下步骤。


一、修改ueditor.config.js配置文件

首先第一步,要完成对配置文件的修改。默认的ueditor配置里,对配置文件的读取是通过controller.jsp完成的,

因为springboot项目中,静态jsp文件的访问是不被允许的,所以我们需要重写这段读取配置文件信息的代码,也就是通过写自己的一个controller来完成这个过程,同时自定义图片和文件上传的位置等信息。

默认的controller.jsp位置如下图:

这时候我们修改配置文件调用资源的接口名称,打开ueditor.config.js,如下图所示:

我通过server_url,拿到了项目的根路径,然后拼接后面的/science-2.0/api/ueditor/config(项目名称/路由名称)拿到完整的访问路径。

二、编写一个新的控制器(CommonController)

这个类就是我们第一步所修改的部分指向的这个控制器,它要完成对config.json文件(该文件位于jsp文件夹下,里面是关于文件上传的一些配置信息)的读取,同时要完成对文件上传的具体实现。

  • 下面我们先来看一下config.json文件(/jsp目录下)

​ 主要看一下图片上传配置的部分:

我们需要修改的部分如图所示:basePath指的是你希望保存的磁盘位置(这个目录最好事先存在),imageActionName是我们处理上传图片功能的那个路由,也就是在controller里是什么,这里就是什么。

下面的文件上传部分类似:

如何使用Spring Boot集成百度UEditor实现图文及文件上传功能?

  • 下面给出完成的controller代码

import com.alibaba.fastjson.JSONException; import com.baidu.ueditor.ActionEnter; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.ClassUtils; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.UUID; import javax.servlet.bs.baidu.com/listicon/'//自定义标号的路径 //,maxListLevel : 3 //限制可以tab的级数, 设置-1为不限制 //,autoTransWordToList:false //禁止word中粘贴进来的列表自动变成列表标签 //fontfamily //字体设置 label留空支持多语言自动切换,若配置,则以配置值为准 ,'fontfamily':[ { label:'',name:'songti',val:'宋体,SimSun'}, { label: '', name: 'SimSun', val: '仿宋,SimSun' }, { label:'',name:'FangSong_GB2312',val:'仿宋_GB2312 ,FangSong_GB2312'}, { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'}, { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'}, { label:'',name:'heiti',val:'黑体, SimHei'}, { label:'',name:'lishu',val:'隶书, SimLi'}, { label:'',name:'andaleMono',val:'andale mono'}, { label:'',name:'arial',val:'arial, helvetica,sans-serif'}, { label:'',name:'arialBlack',val:'arial black,avant garde'}, { label:'',name:'comicSansMs',val:'comic sans ms'}, { label:'',name:'impact',val:'impact,chicago'}, { label:'',name:'timesNewRoman',val:'times new roman'} ] //fontsize //字号 //,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36] //paragraph //段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准 //,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''} //rowspacingtop //段间距 值和显示的名字相同 //,'rowspacingtop':['5', '10', '15', '20', '25'] //rowspacingBottom //段间距 值和显示的名字相同 //,'rowspacingbottom':['5', '10', '15', '20', '25'] //lineheight //行内间距 值和显示的名字相同 //,'lineheight':['1', '1.5','1.75','2', '3', '4', '5'] //customstyle //自定义样式,不支持国际化,此处配置值即可最后显示值 //block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置 //尽量使用一些常用的标签 //参数说明 //tag 使用的标签名字 //label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同, //style 添加的样式 //每一个对象就是一个自定义的样式 //,'customstyle':[ // {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'}, // {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'}, // {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'}, // {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'} //] //打开右键菜单功能 //,enableContextMenu: true //右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准 //,contextMenu:[ // { // label:'', //显示的名称 // cmdName:'selectall',//执行的command命令,当点击这个右键菜单时 // //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName // exec:function () { // //this是当前编辑器的实例 // //this.ui._dialogs['inserttableDialog'].open(); // } // } //] //快捷菜单 //,shortcutMenu:["fontfamily", "fontsize", "bold", "italic", "underline", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist"] //elementPathEnabled //是否启用元素路径,默认是显示 //,elementPathEnabled : true //wordCount //,wordCount:true //是否开启字数统计 //,maximumWords:10000 //允许的最大字符数 //字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示 //,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符 //超出字数限制提示 留空支持多语言自动切换,否则按此配置显示 //,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span> //tab //点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位 //,tabSize:4 //,tabNode:'&nbsp;' //removeFormat //清除格式时可以删除的标签和属性 //removeForamtTags标签 //,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' //removeFormatAttributes属性 //,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign' //undo //可以最多回退的次数,默认20 //,maxUndoCount:20 //当输入的字符数超过该值时,保存一次现场 //,maxInputCount:1 //autoHeightEnabled // 是否自动长高,默认true //,autoHeightEnabled:true //scaleEnabled //是否可以拉伸长高,默认true(当开启时,自动长高失效) //,scaleEnabled:false //,minFrameWidth:800 //编辑器拖动时最小宽度,默认800 //,minFrameHeight:220 //编辑器拖动时最小高度,默认220 //autoFloatEnabled //是否保持toolbar的位置不动,默认true //,autoFloatEnabled:true //浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面 //,topOffset:30 //编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效) //,toolbarTopOffset:400 //设置远程图片是否抓取到本地保存 //,catchRemoteImageEnable: true //设置是否抓取远程图片 //pageBreakTag //分页标识符,默认是_ueditor_page_break_tag_ //,pageBreakTag:'_ueditor_page_break_tag_' //autotypeset //自动排版参数 //,autotypeset: { // mergeEmptyline: true, //合并空行 // removeClass: true, //去掉冗余的class // removeEmptyline: false, //去掉空行 // textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版 // imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版 // pasteFilter: false, //根据规则过滤没事粘贴进来的内容 // clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号 // clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体 // removeEmptyNode: false, // 去掉空节点 // //可以去掉的标签 // removeTagNames: {标签名字:1}, // indent: false, // 行首缩进 // indentValue : '2em', //行首缩进的大小 // bdc2sb: false, // tobdc: false //} //tableDragable //表格是否可以拖拽 //,tableDragable: true //sourceEditor //源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror //注意默认codemirror只能在ie8+和非ie中使用 //,sourceEditor:"codemirror" //如果sourceEditor是codemirror,还用配置一下两个参数 //codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js" //,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js" //codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css" //,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css" //编辑器初始化完成后是否进入源码模式,默认为否。 //,sourceEditorFirst:false //iframeUrlMap //dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径 //,iframeUrlMap:{ // 'anchor':'~/dialogs/anchor/anchor.html', //} //allowLinkProtocol 允许的链接地址,有这些前缀的链接地址不会自动添加app.baidu.com/static/cms/getapikey.html //, webAppKey: "" //默认过滤规则相关配置项目 //,disabledTableInTable:true //禁止表格嵌套 //,allowDivTransToP:true //允许进入编辑器的div标签自动变成p标签 //,rgb2Hex:true //默认产出的数据中的color自动从rgb格式变成16进制格式 // xss 过滤是否开启,inserthtml等操作 ,xssFilterRules: true //input xss过滤 ,inputXssFilter: true //output xss过滤 ,outputXssFilter: true // xss过滤白名单 名单来源: raw.githubusercontent.com/leizongmin/js-xss/master/lib/default.js ,whitList: { iframe: ['frameborder','border','marginwidth','marginheight','width','height','src','id'],//宋雨佳增加这一行 a: ['target', 'href', 'title', 'class', 'style'], abbr: ['title', 'class', 'style'], address: ['class', 'style'], area: ['shape', 'coords', 'href', 'alt'], article: [], aside: [], audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'], b: ['class', 'style'], bdi: ['dir'], bdo: ['dir'], big: [], blockquote: ['cite', 'class', 'style'], br: [], caption: ['class', 'style'], center: [], cite: [], code: ['class', 'style'], col: ['align', 'valign', 'span', 'width', 'class', 'style'], colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'], dd: ['class', 'style'], del: ['datetime'], details: ['open'], div: ['class', 'style'], dl: ['class', 'style'], dt: ['class', 'style'], em: ['class', 'style'], font: ['color', 'size', 'face'], footer: [], h1: ['class', 'style'], h2: ['class', 'style'], h3: ['class', 'style'], h4: ['class', 'style'], h5: ['class', 'style'], h6: ['class', 'style'], header: [], hr: [], i: ['class', 'style'], img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', 'loadingclass', 'class', 'data-latex'], ins: ['datetime'], li: ['class', 'style'], mark: [], nav: [], ol: ['class', 'style'], p: ['class', 'style'], pre: ['class', 'style'], s: [], section:[], small: [], span: ['class', 'style'], sub: ['class', 'style'], sup: ['class', 'style'], strong: ['class', 'style'], table: ['width', 'border', 'align', 'valign', 'class', 'style'], tbody: ['align', 'valign', 'class', 'style'], td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'], tfoot: ['align', 'valign', 'class', 'style'], th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'], thead: ['align', 'valign', 'class', 'style'], tr: ['rowspan', 'align', 'valign', 'class', 'style'], tt: [], u: [], ul: ['class', 'style'], video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style'] } }; function getUEBasePath(docUrl, confUrl) { return getBasePath(docUrl || self.document.URL || self.location.href, confUrl || getConfigFilePath()); } function getConfigFilePath() { var configPath = document.getElementsByTagName('script'); return configPath[ configPath.length - 1 ].src; } function getBasePath(docUrl, confUrl) { var basePath = confUrl; if (/^(\/|\\\\)/.test(confUrl)) { basePath = /^.+?\w(\/|\\\\)/.exec(docUrl)[0] + confUrl.replace(/^(\/|\\\\)/, ''); } else if (!/^[a-z]+:/i.test(confUrl)) { docUrl = docUrl.split("#")[0].split("?")[0].replace(/[^\\\/]+$/, ''); basePath = docUrl + "" + confUrl; } return optimizationPath(basePath); } function optimizationPath(path) { var protocol = /^[a-z]+:\/\//.exec(path)[ 0 ], tmp = null, res = []; path = path.replace(protocol, "").split("?")[0].split("#")[0]; path = path.replace(/\\/g, '/').split(/\//); path[ path.length - 1 ] = ""; while (path.length) { if (( tmp = path.shift() ) === "..") { res.pop(); } else if (tmp !== ".") { res.push(tmp); } } return protocol + res.join("/"); } window.UE = { getUEBasePath: getUEBasePath }; })(); 附config.json

/* 前后端通信相关的配置,注释只允许使用多行方式 */ { "basePath": "D:/scinece-2.0", /* 上传图片配置项 */ "imageActionName": "uploadimage", /* 执行上传图片的action名称 */ "imageFieldName": "upfile", /* 提交的图片表单名称 */ "imageMaxSize": 2048000, /* 上传大小限制,单位B */ "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */ "imageCompressEnable": true, /* 是否压缩图片,默认是true */ "imageCompressBorder": 1600, /* 图片压缩最长边限制 */ "imageInsertAlign": "none", /* 插入的图片浮动方式 */ "imageUrlPrefix":"", /* 图片访问路径前缀 */ "imagePathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */ /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */ /* {time} 会替换成时间戳 */ /* {yyyy} 会替换成四位年份 */ /* {yy} 会替换成两位年份 */ /* {mm} 会替换成两位月份 */ /* {dd} 会替换成两位日期 */ /* {hh} 会替换成两位小时 */ /* {ii} 会替换成两位分钟 */ /* {ss} 会替换成两位秒 */ /* 非法字符 \ : * ? " < > | */ /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */ /* 涂鸦图片上传配置项 */ "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */ "scrawlFieldName": "upfile", /* 提交的图片表单名称 */ "scrawlPathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */ "scrawlUrlPrefix":"", /* 图片访问路径前缀 */ "scrawlInsertAlign": "none", /* 截图工具上传 */ "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */ "snapscreenPathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "snapscreenUrlPrefix":"", /* 图片访问路径前缀 */ "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */ /* 抓取远程图片配置 */ "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"], "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */ "catcherFieldName": "source", /* 提交的图片列表表单名称 */ "catcherPathFormat": "/document/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "catcherUrlPrefix":"", /* 图片访问路径前缀 */ "catcherMaxSize": 2048000, /* 上传大小限制,单位B */ "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */ /* 上传视频配置 */ "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */ "videoFieldName": "upfile", /* 提交的视频表单名称 */ "videoPathFormat": "/document/ueditor/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "videoUrlPrefix": "", /* 视频访问路径前缀 */ "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */ "videoAllowFiles": [ ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */ /* 上传文件配置 */ "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */ "fileFieldName": "upfile", /* 提交的文件表单名称 */ "filePathFormat": "/document/ueditor/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "fileUrlPrefix":"", /* 文件访问路径前缀 */ "fileMaxSize": 307200000, /* 上传大小限制,单位B,默认50MB */ "fileAllowFiles": [ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" ], /* 上传文件格式显示 */ /* 列出指定目录下的图片 */ "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */ "imageManagerListPath": "/document/ueditor/image/", /* 指定要列出图片的目录 */ "imageManagerListSize": 20, /* 每次列出文件数量 */ "imageManagerUrlPrefix":"", /* 图片访问路径前缀 */ "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */ "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */ /* 列出指定目录下的文件 */ "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */ "fileManagerListPath": "/document/ueditor/file/", /* 指定要列出文件的目录 */ "fileManagerUrlPrefix":"", /* 文件访问路径前缀 */ "fileManagerListSize": 20, /* 每次列出文件数量 */ "fileManagerAllowFiles": [ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" ] /* 列出的文件类型 */ }

注意点 1 :如果你是按照我的上一篇随笔完成的对ueditor的初始配置,那么在你引入ueditor控件的那个html文件里,一定存在这么一段代码:

<script type="text/javascript"> window.UEDITOR_HOME_URL = "/UEditor/"; </script>

这次在ueditor.config.js文件中,我指定了这个路径,所以在页面里的这个声明就可以去掉了。而且我留着这里是存在问题的,当然我不太确定是不是这里导致的问题,如果大家配置完没有问题,那这里保留着也可以。

注意点 2 :这里面有几个路径需要再提醒一下

在CommonController中: @RequestMapping("uploadimage")和 @RequestMapping("uploadfile") 需要和 config.json中的imageActionName一一对应。

config.json中:"basePath": "D:/scinece-2.0" 需要是你保存在磁盘的路径,当然这里好像不改也行,因为这里被新写的controller覆盖了,可以尝试不改看看有没有问题,博主保险起见就一起改了。

CommonController 中的 map.put("url", "/PathFile/"+nowName);需要和映射器类的registry.addResourceHandler("/PathImage/**").addResourceLocations("file:/D:/science-2.0/"); 一一对应

CommonController 中的 rootPath = afterPath+ "static/UEditor/jsp";是相对于项目的classpath的路径

对于SpringBoot项目来说,classpath指的是src.main.java和src.main.resources路径以及第三方jar包的根路径,存放在这两个路径下的文件,都可以通过classpath作为相对路径来引用;

因为在maven项目打包之后,会将项目变成如下图所示的路径,也就是说 /java 和 /resources 这两个文件夹所在的路径会消失springboot项目会直接识别这两个文件夹里面的内容,****所以我们写路径的时候就直接可以从 resources 目录的下一级开始,比如从/static或者 /template等等开始。

分享完毕,有不准确的地方大家交流指正,希望对大家有帮助!

好看请赞,养成习惯!