kindEditor结合jfinal的图文上传功能的实现

对于文本编辑器来说,kindEditor是个不错的选择。
我们在输入文本时同时还需要插入一定的图片。
1、首先需要在页面导入kindEditor的相关js。官网:http://kindeditor.net/
只需要留下lang,plugins,themes文件夹和同级的4个js们。
2、页面引入<script type="text/javascript" src="${ctx}/js/kindeditor/kindeditor.js"></script>
3、文本域的相关属性设置,此处只允许输入文本和上传图片。
<textarea class="TextBox Required" style="width: 300px;height:100px;"  name="veVenue.venue_brief" id="venue_brief" ></textarea>
  <script type="text/javascript">
   var options = {
filterMode : false,
items : ['justifyleft',
'justifycenter',
'justifyright',
'justifyfull', '|',
'bold', 'italic','underline','fullscreen','image'
],
afterBlur : function() {
this.sync();
},
themeType : 'oschina',
resizeType : 1,
shadowMode : false,
allowPreviewEmoticons : false,
allowUpload : true, //允许上传图片
allowImageUpload : true,
allowImageRemote : false,
uploadJson : '${ctx}/console/aaa/uploadImg'//上传路径
};
KindEditor.ready(function(K) {
window.editor = K.create('#venue_brief', options);
});
</script>

4、后台方法:
需要导入阿里巴巴开发的fastjson-1.1.28.jar和commons-io-1.4.jar
public void uploadImg() throws Exception{
        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
        
        Map  result = new HashMap();
        String dirName = getPara("dir")==null?"image":getPara("dir");
        String realpath = getRequest().getRealPath("/upload");
        UploadFile uf= getFile("imgFile",realpath);
        String affix_id = "";
        String affix_name = "";
        if(uf!=null){
            affix_name = uf.getFile().getName();
            File file = uf.getFile();
            //检查扩展名
            String fileExt = affix_name.substring(affix_name.lastIndexOf(".") + 1).toLowerCase();
            if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
                result.put("error", 1);
                result.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
                file.delete();
            }else{
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                affix_id = df.format(new Date()) + "_" + new Random().nextInt(1000)+"."+fileExt;
                File savefile = new File(new File(realpath),affix_id);
                FileUtils.copyFile(file, savefile);
                if(file.exists()){
                    file.delete();
                }
                result.put("error", 0);
                result.put("url", JFinal.me().getContextPath()+"/upload/"+affix_id);
            }
        }else{
            result.put("error", 1);
            result.put("message", "请选择文件");
        }
        
        render(new JsonRender(JSON.toJSONString(result)).forIE());
    }

你可能感兴趣的:(html)