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;
}
}