wangeditor圖片上傳的方法簡單例項
阿新 • • 發佈:2019-02-07
js部分
<script type="text/javascript"> var E = window.wangEditor var editor = new E('#editor'); editor.customConfig.uploadImgServer = root + "fileLssue/upload1.do"; //上傳URL editor.customConfig.uploadFileName = 'myFileName'; editor.customConfig.uploadImgHooks = { customInsert: function (insertImg, result, editor) { // 圖片上傳並返回結果,自定義插入圖片的事件(而不是編輯器自動插入圖片!!!) // insertImg 是插入圖片的函式,editor 是編輯器物件,result 是伺服器端返回的結果 debugger; // 舉例:假如上傳圖片成功後,伺服器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片: var url =result.data; insertImg(url); // result 必須是一個 JSON 格式字串!!!否則報錯 } } editor.create(); </script>
java後臺程式碼
/** * 檔案上傳 * @param * @return * @throws IOException */ @ResponseBody @RequestMapping(value = "upload1.do") public Result upload2 (@RequestParam(value="myFileName") MultipartFile file) throws IOException { //MultipartFile 轉換成檔案 String fileName=file.getOriginalFilename(); //獲取到專案路徑 String savePath = new File("").getCanonicalPath(); if(file.getSize()>0) { try { String path = SaveFileFromInputStream(file.getInputStream(), savePath, fileName); Map<String,Object> map = new HashMap<String,Object>(); map.put("imgUrl",path); return new Result(map); } catch (IOException e) { e.printStackTrace(); return new Result(null); } }else{ return new Result(null); } } /**儲存的 * @param stream * @param savePath * @param filename * @return * @throws IOException */ public String SaveFileFromInputStream(InputStream stream,String savePath,String filename) throws IOException { //初始化日期格式 SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS"); //以當前日期作加下劃線加舊的檔名作為上傳檔案儲存的名稱 String newFileName = sd.format(new Date()) + "_" + filename; String savePathAndFileName = savePath + "/"+ newFileName; FileOutputStream fs=new FileOutputStream(savePathAndFileName); byte[] buffer =new byte[1024*1024]; int bytesum = 0; int byteread = 0; while ((byteread=stream.read(buffer))!=-1) { bytesum+=byteread; fs.write(buffer,0,byteread); fs.flush(); } fs.close(); stream.close(); return savePathAndFileName; }