异常:图片能上传但不能回显到前端编辑器中!!!
解决:利用ssm(spring) 实现图片上传,可以轻松回显到前端,但springboot默认是内置tomcat,该将图片上传到哪里呢?
将ssm中图片上传的代码用到springboot项目中依然不行,网上的都不可行!
后来才知道在springboot中不是将项目上传到webroot下面,也不是上传到缓存中,而是上传到运行资源中,也就是target目录中的static的某个文件夹中,而不是源代码static的某个文件中,那么怎么获取到运行状态(编译状态)staitc文件目录呢? 通过这行代码:
String path= Class.class.getClass().getResource("/").getPath(); path= path+"static"+File.separator+"uploadfiles";
这样就能指定到运行目录根目录+static+uploadfiles文件夹,然后其他的图片上传操作基本不变即可(同ssm模式基本一致),下面附上代码:
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/* * 上传图片 */ @RequestMapping(value = "/upload1.html", produces = {"text/html;charset=UTF-8"},method=RequestMethod.POST) @ResponseBody public Object uploadReportFile(@RequestParam(value = "myFileName", required = false) MultipartFile cardFile, HttpServletRequest request,HttpSession session) { String path= Class.class.getClass().getResource("/").getPath(); path= path+"static"+File.separator+"uploadfiles"; Map<String, String> map = new HashMap<String, String>(); String jo=""; if(cardFile != null){ String oldFileName = cardFile.getOriginalFilename(); String prefix=FilenameUtils.getExtension(oldFileName); if(cardFile.getSize() > 5000000){ return "1"; }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){ String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_IDcard.jpg"; File targetFile = new File(path, fileName); // 检测是否存在目录 if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } try { cardFile.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } String url =request.getContextPath()+"/static/uploadfiles/"+fileName; map.put("data", url); jo = JSONArray.toJSONString(map); return jo; }else{ return "2"; } } return null; }
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
前台js初始化wangEditor, 并将后台的传送过来的url插入到:
//初始化编辑器 var E = window.wangEditor; var editor = new E('#editor'); editor.customConfig.showLinkImg = false; editor.customConfig.uploadFileName = 'myFileName'; editor.customConfig.uploadImgServer = '/upload1.html'; editor.customConfig.uploadImgHooks = { customInsert: function (insertImg, result, editor) { var url =result.data; insertImg(url); } }; editor.create();
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
其他wangEditor异常处理:
//获取content.并将所有的多余空格去除 var text=$("#contentVal").val().replace(/\s+/g, ""); text=text.replace("imgsrc", "img src"); //将转义符反译为html // var htmltext=HTMLDecode(text); editor.txt.html(text); ReportInfoDlg.editor = editor;