HTML页面:
<div id="editor">
//此处创建富文本区域
</div>
<script> $(function () { var E = window.wangEditor var editor = new E('#editor') // 隐藏“网络图片”tab editor.customConfig.showLinkImg = false // 关闭粘贴内容中的样式 editor.customConfig.pasteFilterStyle = false // 忽略粘贴内容中的图片 editor.customConfig.pasteIgnoreImg = false // 将图片大小限制为 3M editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024 // 限制一次最多上传 1 张图片 editor.customConfig.uploadImgMaxLength = 1 editor.customConfig.uploadImgServer = '/upload' editor.customConfig.uploadFileName = 'myFileName' /* editor.customConfig.uploadImgHeaders = { 'Accept': 'text/x-json' }*/ editor.customConfig.uploadImgHooks = { customInsert: function (insertImg, result, editor) { var url =result.data;//获取后台返回的url insertImg(url); } }; editor.create(); $('#editor').attr('style','height:auto;'); }) </script>
后端代码:
创建一个配置类:MyWebMvcConfigurerAdapter
内容如下:
@Configuration public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry){ //指向外部目录 registry.addResourceHandler("param1").addResourceLocations("param2"); super.addResourceHandlers(registry); } } 注:param1是指定的要上传的文件夹位置(去掉盘符,在最后添加“/**” 例如:“imgUploads/**”)param2是指定的文件夹位置(带盘符,在前面要加上“file” 例如:“file:D:/imgUploads/”)
controller层:
@RequestMapping("/upload") @ResponseBody public Map<String, String> upload(@RequestParam(value="myFileName") MultipartFile file, HttpServletRequest request) { String separator = System.getProperty("file.separator"); separator=separator.replaceAll("\\\\","/"); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+ separator; //获取项目路径+端口号 比如:http://localhost:8080/ try { String filePath=""; //获取源文件 filePath="D:/imgUploads/" ;//存储地址,此处也可以在application.yml中配置对象用@Value("${*.**}")注解注入内容 String filename = file.getOriginalFilename();//获取图片名 String[] names=filename.split("\\.");//获取后缀格式 String uploadFileName=UUID.randomUUID().toString()+"."+names[names.length-1];//生成新图片 File targetFile = new File (filePath,uploadFileName);//目标文件 if (!targetFile.getParentFile().exists()){ targetFile.getParentFile().mkdirs(); } //传图片一步到位 file.transferTo(targetFile); Map<String, String> map = new HashMap<String, String>(); map.put("data",basePath+"imgUploads/"+uploadFileName);//这里应该是项目路径,返回前台url return map; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }