最近在使用一个wangEditor富文本编辑器,这个富文本编辑器有一个上传文件的功能,搞了两天的时间终于终于可以成功的删除上传图片了,
遇到的问题一共有两个,一个是我使用SpringMVC,一开始上传文件后台是无法接收到的,也就是文件被拦截了
还有一个问题是是后台返回的数据格式不对,所以虽然说文件是上传到我们对应的文件夹里面了,但是前台还是一直提示文件上传错误
现在我是讲最终的展示出来,应该可以直接拿去用了:
var editor = new wangEditor('#txtDiv'); editor.customConfig.uploadImgServer = serviceUrl+'/Shopping/filecontroller/uploadfile'; /* editor.customConfig.uploadImgFileName = 'myFileName';*/ editor.customConfig.uploadImgShowBase64 = true; editor.customConfig.showLinkImg = false; editor.customConfig.debug=true; editor.customConfig.uploadImgHooks = { success: function (xhr, editor, result) { // 图片上传并返回结果,图片插入成功之后触发 // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果 console.log(result); } } editor.create();
创建wangEditor编辑器,
对应的后台java文件的是:
@RequestMapping(value = "/uploadfile") public String uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("-------------------开始调用上传文件uploadfile接口-------------------"); String path = this.getClass().getClassLoader().getResource("/").getPath(); int index = path.indexOf("Shopping"); path = path.substring(0, index + "Shopping".length()) + "/WebContent/resources/upload/"; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setHeaderEncoding("UTF-8"); // 处理中文问题 sfu.setSizeMax(1024 * 1024); // 限制文件大小 String fileName = ""; try { List<FileItem> fileItems = sfu.parseRequest(request); for (FileItem item : fileItems) { fileName = UUID.randomUUID().toString() + item.getFieldName() .substring(item.getFieldName().lastIndexOf('.'), item.getFieldName().length()); item.write(new File(path + "//" + fileName)); } } catch (Exception e) { e.printStackTrace(); } // 获取图片url地址 JSONObject json=new JSONObject(); JSONArray arr=new JSONArray(); String imgUrl = "http://localhost:8080/Shopping/resources/upload/" + fileName; arr.add(imgUrl); json.put("errno", 0); json.put("data", arr); response.setContentType("text/text;charset=utf-8"); PrintWriter out = response.getWriter(); out.print(json.toString()); out.flush(); out.close(); log.info("-------------------结束调用上传文件uploadfile接口-------------------"); return "nihao"; }
这样前台就可以正常的插入图片了
希望对你有所帮助