一、简介
wangeditor富文本编辑器是由js和css开发的富文本编辑器,轻量、简洁、高效
详细信息可以查看官网:http://www.wangeditor.com/
二、上传图片
本章内容主要讲使用js语言上传图片至服务器保存
1、第一步
调用官网静态资源
<link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
<script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
2、第二步
const {createEditor,createToolbar}=window.wangEditor;//创建实例对象
const editorConfig={
MENU_CONF:{},
withCredentials:true,//定义该属性为ture表示允许跨域访问
autofocus:false,
scroll:false,
maxLength:1200,
minLength:200,
};
editorConfig.MENU_CONF['uploadImage']={//向编辑器中上传图片或者粘贴图片时触发该方法
fieldName:'image',
server:'http://192.168.178.44:8888/upImage',//后台服务器地址
maxFileSize: 6 * 1024 * 1024, //
maxNumberOfFiles: 200,
// allowedFileTypes: ['image/*'],
// timeout: 20 * 1000, // 5 秒
};
我们在前端上传图片时,编辑器会将图片上传至后台服务器进行保存我的地址为'http://192.168.178.44:8888/upImage',并返回图片地址在编辑器上回显。返回数据开始必须为以下结构(上传成功、上传失败),否则会报错。
{
"errno": 0, // 注意:值是数字,不能是字符串
"data": {
"url": "xxx", // 图片 src ,必须
"alt": "yyy", // 图片描述文字,非必须
"href": "zzz" // 图片的链接,非必须
}
}
{
"errno": 1, // 只要不等于 0 就行
"message": "失败信息"
}
三、服务器端方法实现
@CrossOrigin
@ResponseBody
@RequestMapping(value = "/upImage")
public Object upImage(MultipartFile image) {
String filePath = "D:\\IntelliJ IDEA 2019.3.3\\IDEA project\\retry\\src\\main\\resources\\static\\picture\\";
String suffix = "";
try {
String originalFilename = image.getOriginalFilename();
if (originalFilename.contains(".")) {
suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
}
String fileName=System.currentTimeMillis()+suffix;
File targetFile = new File(filePath, fileName);
if(!targetFile.exists()){
targetFile.createNewFile();
}
try {
image.transferTo(targetFile);
} finally {
}
String url="http://localhost:8888/static/"+fileName;
JSONObject jsonObject=new JSONObject();
JSONObject jsonObject1=new JSONObject();
System.out.println(url);
jsonObject1.put("url",url);
jsonObject.put("errno",0);
jsonObject.put("data",jsonObject1);
return jsonObject;
} catch (Exception e) {
JSONObject jsonObject=new JSONObject();
jsonObject.put("errno",1);
jsonObject.put("message","失败信息");
return jsonObject;
}
}
CrossOrigin注释表示允许跨域访问
四、测试
使用编辑器需要启动后台服务

图片粘贴成功!
到服务器本地查看图片是否存在


前沿知识,制作不易!
本章至此结束!祝各位好运!