引入js文件
<script type="text/javascript" src="style/js/wangEditor.min.js"></script>
新建div名字任意
<div id="editor">
</div>
创建富文本编辑器
var E = window.wangEditor;
var editor = new E('#editor');
editor.customConfig.uploadImgServer = '<%=path%>/Img/upload'; //上传URL
editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
editor.customConfig.uploadImgMaxLength = 5;
editor.customConfig.uploadFileName = 'myFileName';
editor.customConfig.uploadImgHooks = {
customInsert: function (insertImg, result, editor) {
// 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
// insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果 // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
var url =result.data;
insertImg(url); // result 必须是一个 JSON 格式字符串!!!否则报错
}
}
editor.create();
后台代码 smm框架
public class ImgController {
@Autowired
private HttpServletRequest request;
@RequestMapping(value ="/upload",method=RequestMethod.POST)
@ResponseBody
public Object UpLoadImg(@RequestParam(value="myFileName")MultipartFile mf) {
String realPath = request.getSession().getServletContext().getRealPath("upload"); //获取源文件
String filename = mf.getOriginalFilename();
String[] names=filename.split("\\.");//
String tempNum=(int)(Math.random()*100000)+"";
String uploadFileName=tempNum +System.currentTimeMillis()+"."+names[names.length-1];
File targetFile = new File (realPath,uploadFileName);//目标文件 //开始从源文件拷贝到目标文件 //传图片一步到位
try {
mf.transferTo(targetFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} Map<String, String> map = new HashMap<String, String>();
map.put("data","http://localhost:8080/SSM/upload/"+uploadFileName);//这里应该是项目路径
return map;//将图片地址返回
}
}