本文主要是介绍Spring Boot项目百度UEditor上传图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
业务背景
- spring boot项目
- 实现富文本框
- 上传图片到富文本框中,可新增、编辑
- 图片保存在独立的FastDFS服务器上
开发步骤
下载源码
- UEditor官网下载地址
- 我下载的版本是【1.4.3.3 Jsp 版本】UTF-8版
将源码放到项目指定位置
- 示例如下
加入指定JAR依赖
- 具体JAR在 \ueditor\jsp\lib 下
- POM文件中示例【即ueditor-1.1.2.jar】
<dependency><groupId>cn.songxinqiang</groupId><artifactId>com.baidu.ueditor</artifactId><version>1.1.2-offical</version>
</dependency>
源码重要介绍
ueditor/ueditor.config.js
/ueditor/jsp/config.json
ueditor/jsp/controller.jsp
后端请求规范
文档详情
图片上传完成时,为使得图片在富文本框中成功回显,上传方法返回的JSON数据格式必须和官方文档规定的保持一致,格式如下
{"state": "SUCCESS","url": "upload/demo.jpg","title": "demo.jpg","original": "demo.jpg"
}
覆盖默认的请求地址
action的配置对应【 /ueditor/jsp/config.json】中的 “imageActionName”: “uploadimage”, /* 执行上传图片的action名称 */
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {// 这里很重要,很重要,很重要,要和配置中的imageActionName值一样if (action == 'uploadimage') { // 这里调用后端我们写的图片上传接口return 'commonQuestionsQuery/uploadImageData';} else {return this._bkGetActionUrl.call(this, action);}
}
后台代码
- 类UeditorImage源码
package com.sto.customerapp.entity;public class UeditorImage {private String state; private String url; private String title; private String original; public String getState() {return state;}public void setState(String state) {this.state = state;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getOriginal() {return original;}public void setOriginal(String original) {this.original = original;}}
- Handler中源码
@RequestMapping("/uploadImageData")
@ResponseBody
public String uploadImageData(HttpServletRequest request) {Gson gson = new Gson();UeditorImage msg = uploadFile(request);return gson.toJson(msg);
}private UeditorImage uploadFile(HttpServletRequest request) {UeditorImage image = new UeditorImage();List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("upfile");try {String fileName = files.get(0).getOriginalFilename();logger.info("接收到上传数据,图片名称为 :" + fileName);String path = fastdfsClient.uploadFile(files.get(0), "", false);logger.info("图片上传成功,上传路径为 :" + serverPath + path);image.setUrl(serverPath + path);image.setState("SUCCESS");image.setOriginal(fileName);image.setTitle(fileName);} catch (IOException e) {e.printStackTrace();logger.error("图片上传失败,失败原因:" + e.getMessage());image.setState("FAIL");}return image;
}
这篇关于Spring Boot项目百度UEditor上传图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!