SpringMVC整合富文本编辑器

1,396 阅读2分钟

开发系统的时候,需要整合富文本编辑器功能。我使用的wangEditor,这个编辑器清爽、简便,该有的功能都有了,非常好用。

如需使用,可访问官网

在系统开发中使用SpringMVC整合wangEditor

后端开发

因为涉及到上传图片,所以需要上传配置。

后端上传配置

1、上传所需Jar包

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
</dependency>

2、SpringMVC的xml 配置

<!-- 文件上传解析器 -->
<bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 设置上传文件的最大尺寸为5MB -->
   <property name="maxUploadSize">
   	<value>5242880</value>
   </property>
</bean>

3、代码编写

@Value("${info.upload}")
private String path;

@Autowired
private InfomationService infomationService;

@CrossOrigin //跨域访问
@RequestMapping(value="/save",method=RequestMethod.POST)
@ResponseBody
public Map<String,Object> save(@RequestParam("inputfile") MultipartFile inputfile){
   Map<String,Object> map = new HashMap<>();
   if(!inputfile.isEmpty()){
   	map.put("errno", 0);
   	//设置新的图片名
   	String fileStr=inputfile.getOriginalFilename();
   	String newFilename=UUID.randomUUID().toString()+
   	            ileStr.substring(fileStr.lastIndexOf("."));
   	//将图片保存到硬盘
   	try {
   		inputfile.transferTo(new File(path+newFilename));
   	} catch (IllegalStateException | IOException e) {
   		e.printStackTrace();
   	}
   	//文件地址
   	String[] data = new String[]{".../infoimg/"+newFilename};
   	map.put("data", data);
   }
   return map;
}

上面我只提供了单文件上传,但是编辑器的文件地址是数组类型的。

前端开发

引入JS

script src=".../js/wangEditor.min.js"></script>

wangEditor配置

var E = window.wangEditor;
var editor = new E('#editor');
// 或者 var editor = new E( document.getElementById('editor') )

//后端保存图片的孩子
editor.customConfig.uploadImgServer = '.../save';
//上传图片数量
editor.customConfig.uploadImgMaxLength = 1;
//上传图片名称
editor.customConfig.uploadFileName = 'inputfile';

editor.create();
   

图片上传返回数据

{
   // errno 即错误代码,0 表示没有错误。
   //       如果有错误,errno != 0,
   //可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
   "errno": 0,

   // data 是一个数组,返回若干图片的线上地址
   "data": [
       "图片1地址",
       "图片2地址",
       "……"
   ]
}

wangEditor使用简单方便,而且界面清爽很干净,非常推荐使用。