1. 程式人生 > >wangEditor富文字編輯器使用及圖片上傳

wangEditor富文字編輯器使用及圖片上傳

<script type="text/javascript" src="style/js/wangEditor.min.js"></script>

<div id="editor">
</div>

建立富文字編輯器

var E = window.wangEditor;
var editor = new E('#editor');
editor.customConfig.uploadImgServer = '<%=path%>/Img/upload'; //上傳URL
editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
editor.customConfig.uploadImgMaxLength = 5;    
editor.customConfig.uploadFileName = 'myFileName';
editor.customConfig.uploadImgHooks = {
    customInsert: function (insertImg, result, editor) {
                // 圖片上傳並返回結果,自定義插入圖片的事件(而不是編輯器自動插入圖片!!!)
                // insertImg 是插入圖片的函式,editor 是編輯器物件,result 是伺服器端返回的結果
         
                // 舉例:假如上傳圖片成功後,伺服器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
                var url =result.data;
                insertImg(url);
         
                // result 必須是一個 JSON 格式字串!!!否則報錯
            }
        }
        editor.create();

後臺程式碼 smm框架

public class ImgController {
    @Autowired 
    private HttpServletRequest request; 
    @RequestMapping(value ="/upload",method=RequestMethod.POST)
    @ResponseBody
    public Object UpLoadImg(@RequestParam(value="myFileName")MultipartFile mf) {
        String realPath = request.getSession().getServletContext().getRealPath("upload");
         
    //獲取原始檔
    String filename = mf.getOriginalFilename();
    String[] names=filename.split("\\.");//
    String tempNum=(int)(Math.random()*100000)+"";
    String uploadFileName=tempNum +System.currentTimeMillis()+"."+names[names.length-1];
    File targetFile = new File (realPath,uploadFileName);//目標檔案
     
    //開始從原始檔拷貝到目標檔案
     
    //傳圖片一步到位
    try {
        mf.transferTo(targetFile);
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     
    Map<String, String> map = new HashMap<String, String>();
    map.put("data","http://localhost:8080/SSM/upload/"+uploadFileName);//這裡應該是專案路徑
    return map;//將圖片地址返回
    }
}