SpringBoot+WangEditor上傳圖片
阿新 • • 發佈:2018-11-14
今天本地在除錯一個問題,,wangEditor這個富文字編輯器上傳圖片,其實上傳圖片到也沒有什麼困難的地方,關鍵是在於,後臺是SpringBoot來進行接收圖片,,不說了直接上程式碼:這個是前端的程式碼:
var editor = new wangEditor('#txtDiv'); editor.customConfig.uploadImgServer = localhostPaht+projectName+'/filecontroller/uploadImg'; editor.customConfig.uploadImgShowBase64 = true; /* editor.customConfig.uploadImgFileName = 'myFileName';*/ editor.customConfig.uploadFileName = 'myFileName'; editor.customConfig.showLinkImg = false; /* editor.customConfig.debug=true;*/ editor.customConfig.uploadImgHooks = { success: function (xhr, editor, result) { } } editor.create();
那麼後臺應該如何進行編寫:
@RequestMapping(value = "/uploadImg", method = RequestMethod.POST) @ResponseBody public void uploadImg(@RequestParam(value = "myFileName", required = false) MultipartFile cardFile, HttpServletRequest request, HttpServletResponse response) { System.out.println("*************接收上傳檔案*************"); try { if (cardFile != null) { String oldFileName = cardFile.getOriginalFilename();// 獲取檔名稱 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = sdf.format(new Date()) + "_" + oldFileName; String realPath = PropertiesUtil.getValue("FILEPATH", "fileconfig.properties"); File targetFile = new File(realPath, newFileName); // 檢測是否存在目錄 if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } // cardFile.transferTo(targetFile); BufferedOutputStream out1 = new BufferedOutputStream(new FileOutputStream(targetFile)); out1.write(cardFile.getBytes()); out1.flush(); out1.close(); if(targetFile.exists()){ System.out.println("檔案已經存在"); } JSONObject json = new JSONObject(); JSONArray arr = new JSONArray(); String ipconfigstr = PropertiesUtil.getValue("IPCONFIG", "fileconfig.properties"); String imgUrl = "http://" + ipconfigstr + "/Sqzp/images/" + newFileName; 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(); } else { System.out.println("************上傳檔案為空***************"); } System.out.println("*************接收上傳檔案結束*************"); } catch (Exception e) { e.printStackTrace(); } }
但是也存在一個問題就是在Ecplise進行開發的過程中,上傳到圖片是沒有辦法直接回顯到編輯器上的,但是可以看到的是但是當我們更新到伺服器上面之後會發現,圖片是可以正常的顯示到編輯器上面的
wangEditor + SpringBoot 是可以正常的顯示出來的
如果大家有什麼疑問可以下面加我的微信,歡迎一起學習交流: