KingEditor结合SpringMVC上传图片

来源:互联网 发布:淘宝如何避免售假违规 编辑:程序博客网 时间:2024/05/16 18:33

1.在官网上下载压缩包解压后放入项目下,在使用编辑器的压面导入js脚本:

<script src="${pageContext.request.contextPath}/kindeditor/kindeditor.js" type="text/javascript" ></script>
<script src="${pageContext.request.contextPath}/kindeditor/lang/zh_CN.js" type="text/javascript" ></script>

2.在需要使用编辑器的地方加入下代码

<textarea id="editor_id" name="content" style="width:900px;height:600px;"></textarea>  
<script type="text/javascript"> 

//初始化编辑器
var editor;
      KindEditor.ready(function(K) {  
                  editor = K.create('#editor_id',{
              uploadJson : '<%=request.getContextPath()%>/policyController/fileUpload', //图片上传
              fileManagerJson :'<%=request.getContextPath()%>/policyController/fileManager',  
              allowFileManager : true,
              items : ['source', '|', 'undo', 'redo', '|', 'preview', 'template', 'cut', 'copy', 'paste',
              'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
              'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
              'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
              'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
              'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image','multiimage',
              'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
              'anchor', 'link', 'unlink']
              }); 
               editor.html(“”)  //赋值editor_id
      });  
</script>

3.图片上传(本地上传)

 uploadJson属性指定图片上传路径,这里我写的是SpringMVC上传路径

后台代码如下:

//图片上传
 @RequestMapping(value = "/fileUpload", produces = "text/html;charset=UTF-8")  
@ResponseBody  
public void fileUpload(@RequestParam(value = "imgFile", required = false) MultipartFile file,
    HttpServletRequest request, HttpServletResponse response)  throws Exception{  
PrintWriter out = response.getWriter();
PageData pd = this.getPageData();
//文件保存本地目录路径
String savePath=“d:/uploadFile/”;
//文件读取URL
String saveUrl=request.getContextPath()+"/policyController/attached";
    String dirName = pd.getString("dir");  
    if (dirName == null) {  
        dirName = "image";  
    }  
    //定义允许上传的文件扩展名  
    Map<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,xml,txt,zip,rar,gz,bz2");  
    if(!extMap.containsKey(dirName)){  
       out.println(fileUploadUtils.getError("目录名不正确。"));  
    }  
    //创建文件夹  
    savePath += dirName + "/";  
    File saveDirFile = new File(savePath);  
    if (!saveDirFile.exists()) {  
         saveDirFile.mkdirs();  
    }  
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
    String ymd = sdf.format(new Date());  
    savePath += ymd + "/";  
    File dirFile = new File(savePath);  
    if (!dirFile.exists()) {  
        dirFile.mkdirs();  
    }  
    if(!file.isEmpty()){
      String fileName=file.getOriginalFilename();
      //检查扩展名  
      String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
      if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){  
        out.println(fileUploadUtils.getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
      }  
       
      SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
      String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
      try{  
        File infoFile = new File(savePath, newFileName);  
    InputStream is=file.getInputStream();
    FileOutputStream fos = new FileOutputStream(infoFile);
    byte[] bs = new byte[is.available()];
    int len=is.read(bs);
    while(len!=-1) {
    fos.write(bs, 0, len);
    len=is.read(bs);
    }
    is.close();
    fos.flush();
    fos.close(); 
     }catch(Exception e){  
        out.println(fileUploadUtils.getError("上传文件失败。"));
     }  
       
      JSONObject obj = new JSONObject();
      obj.put("error", 0);
      obj.put("url", saveUrl+"?savePath="+savePath+newFileName);
      out.println(obj.toJSONString());
     } 
         
}  


 /**
 * 
* @Title: attached 
* @Description: 从本地读取刚上传的文件 
* @author  
* @param 
* @return void    返回类型 
* @throws ServiceException
 */
@RequestMapping(value = "/attached", produces = "text/html;charset=UTF-8")  
public void attached(HttpServletRequest request, HttpServletResponse response) {  
   response.setContentType("text/html; charset=UTF-8");  
   PageData pd = new PageData();//用于接收参数的一个类
    pd = this.getPageData();
   InputStream is = null;  
   OutputStream os = null;  
   try {  
       File file = new File(pd.get("savePath").toString());  //返回的url的图片上传地址
       is = new FileInputStream(file);  
       byte[] buffer = new byte[is.available()];  
       is.read(buffer);  
       os = new BufferedOutputStream(response.getOutputStream());  
       os.write(buffer);  
       os.flush();  
   } catch (Exception e) {  
       e.printStackTrace();
   } finally {  
        if (is != null) {  
           try {  
               is.close();  
           } catch (IOException e) {  
               e.printStackTrace();
           }
        }
        if (os != null) {  
           try {  
               os.close();  
           } catch (IOException e) {  
               e.printStackTrace();  
           }  
        }  
   }  
}