ckeditor上传图片示例

1、修改config.js 

CKEDITOR.editorConfig = function (config) {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';
    config.width = '500';
    config.height = '100';
    config.removePlugins = 'elementspath';
    config.allowedContent = true;
    // 按回车键 显示</br>
    config.enterMode = CKEDITOR.ENTER_BR;
    // 输出html四题
    config.basicEntities = false;
    config.tabSpaces = 4;
    // config.removeButtons = 'Source,Save,NewPage,Preview,Print,Templates,Cut,Copy,Paste,PasteText,PasteFromWord,Undo,Redo,Find,Replace,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Bold,Italic,Underline,Strike,Subscript,Superscript,RemoveFormat,NumberedList,BulletedList,Outdent,Indent,Blockquote,CreateDiv,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock,BidiLtr,BidiRtl,Link,Unlink,Anchor,Image,Flash,Table,HorizontalRule,Smiley,SpecialChar,PageBreak,Maximize,ShowBlocks,About,Styles,Format,Font,Iframe,BGColor,FontSize'
    // config.removeButtons = '源码,保存,新建,预览,打印,模板,剪切,复制,粘贴,粘贴为无文本格式,从 MS WORD 粘贴,撤销,重做,查找,替换,全选,即时拼写检查,表单,复选框,单选框,单行文本,多行文本,列表/菜单,按钮,图片按钮,隐藏域,加粗,倾斜,下划线,删除线,下标,上标,清除格式,编号列表,项目列表,减少缩进量,增加缩进量,块引用,创建div容器,左对齐,居中,右对齐,两端对齐,文字方向从左到右,文字方向从右到左,插入/编辑超链接(上传文件),取消超链接,插入/编辑锚点链接,图像,flash,表格,插入水平线,插入表情,插入特殊符号,插入分页符,全屏,显示区块,关于,样式快捷方式,文本格式,字体,iframe,背景色,字体大小'
    config.toolbar = [['Preview', '-', 'TextColor', '-', 'Cut', 'Copy', 'Paste', '-', 'Undo', 'Redo', '-', 'Maximize', '-', 'filling','-', 'Image']];
    config.extraPlugins += (config.extraPlugins ? ',filling' : 'filling');
    //上传到服务器的路径
    config.filebrowserUploadUrl ='/noticeManage/uploadImage.asp?command=QuickUpload&type=Files';
};

2、修改image.js

        a.删除image.js中包含在双引号中的文本

 

        b、将Upload 修改为false

 

3、java代码(本人使用的新版,老版本为注释掉的部分)

        新版本最后是有返回值的,而旧版本是没有返回值的。

/**
   * 上传图片
   */
//  @AclResource(resourceId = ACL.NOTICEMANAGE_BUTTON_UPLOAD)
  @RequestMapping("/uploadImage")
  @ResponseBody
  public Map<String, Object> PublicUtilController(HttpServletRequest request,
                                                  HttpServletResponse response,
                                                  HttpSession session, @RequestParam MultipartFile[] upload) {
    return uploadImage(request, response, session, upload);
  }

  /**
   * 上传图片
   *
   * @param request
   * @param response
   * @param session
   * @param upload
   */
  public Map<String, Object> uploadImage(HttpServletRequest request, HttpServletResponse response, HttpSession session, MultipartFile[] upload) {
    response.setCharacterEncoding("UTF-8");
//    是否成功
    int isSuccess=WebsiteConstant.FAILED;
//    PrintWriter out = null;
//
//    try {
      out = response.getWriter();
//    } catch (IOException e1) {
//      log.error("response.getWriter()异常=" + e1);
//      e1.printStackTrace();
//    }
//    String callback = request.getParameter("CKEditorFuncNum");

    // 获得response,request
    Map<String, Object> m = new HashMap<String, Object>();

    if (!ServletFileUpload.isMultipartContent(request)) {
      m.put("error", 1);
      m.put("message", "请选择文件!");
      log.info("请选择文件!");
      return m;
    }

    String originalFileName = null;//上传的图片文件名
    String fileExtensionName = null;//上传图片的文件扩展名
    if (1 < upload.length) return m;
    MultipartFile file = upload[0];
    if (file.getSize() > 10 * 1024 * 1024) {
//      out.println("<script type=\"text/javascript\">");
//      out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
//              + ",''," + "'文件大小不得大于10M');");
//      out.println("</script>");
      m.put("error", 1);
      m.put("message", "文件过大!");
      log.info("文件过大!");
      return m;

    }

    originalFileName = file.getOriginalFilename();
    log.info("上传的图片文件名=" + originalFileName);
    fileExtensionName = originalFileName.substring(
            originalFileName.lastIndexOf(".")).toLowerCase();
    log.info("图片文件扩展名=" + fileExtensionName);

    String[] imageExtensionNameArray = WebsiteConstant.IMAGE_EXTENSION_NAME_ARRAY;

//    String allImageExtensionName = "";
    boolean isContain = false;//默认不包含上传图片文件扩展名
    for (int i = 0; i < imageExtensionNameArray.length; i++) {
      if (fileExtensionName.equals(imageExtensionNameArray[i])) {
        isContain = true;
      }
//      if (i == 0) {
//        allImageExtensionName += imageExtensionNameArray[i];
//      } else {
//        allImageExtensionName += " , " + imageExtensionNameArray[i];
//      }

    }

    String newFileName = UUID.randomUUID() + fileExtensionName;
    String imageUrl="";
    String uploadPath;
    if ((!System.getProperties().getProperty("os.name").toLowerCase().contains("linux"))) {
      uploadPath = WebsiteConstant.PIC_APP_FILE_SYSTEM_CKEDITOR_LOCATION;

    } else {
      uploadPath = WebsiteConstant.PIC_APP_FILE_SYSTEM_CKEDITOR_SERVICE;
    }
    if (isContain) {//包含
      File pathFile = new File(uploadPath);
      if (!pathFile.exists()) { // 如果路径不存在,创建
        pathFile.mkdirs();
      }
      try {
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadPath, newFileName));
//    InputStream is=file.getInputStream();
//    File toFile = new File(uploadPath, newFileName);
//    OutputStream os = new FileOutputStream(toFile);
//    byte[] buffer = new byte[1024];
//    int length = 0;
//    while ((length = is.read(buffer)) > 0) {
//     os.write(buffer, 0, length);
//    }
//    is.close();
//    os.close();
      } catch (IOException e) {
        log.error("FileUtils.copyInputStreamToFile uploadPath=" + uploadPath + " newFileName =" + newFileName + " exception=" + e);
      }
      imageUrl = WebsiteConstant.PIC_APP_SERVER_URL + newFileName;
      isSuccess=WebsiteConstant.SUCCESS;
      // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url
//      out.println("<script type=\"text/javascript\">");
//      out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
//              + ",'" + imageUrl + "','')");
//      out.println("</script>");
//        out.write("window.parent.CKEDITOR.tools.callFunction(" + callback
//                + ",'" +imageUrl + "','')"+"</script>");

    } else {
//      out.println("<script type=\"text/javascript\">");
//      out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
//              + ",''," + "'文件格式不正确(必须为" + allImageExtensionName + "文件)');");
//      out.println("</script>");
      m.put("error", 1);
      m.put("message", "请上传图片文件!");
      log.info("请上传图片文件!");
      return m;
    }
    m.put("uploaded", isSuccess);
    m.put("fileName", newFileName);
    m.put("url", imageUrl);
    return m;

  }
public class WebsiteConstant {
  /**
   * 格式
   */
  public static String[] IMAGE_EXTENSION_NAME_ARRAY={".jpg",".jpeg",".png",".gif",".bmp"};
  /**
   *
   */
  public static final String PIC_APP_FILE_SYSTEM_CKEDITOR_SERVICE = "/"  +"data/"+ "images/";
  public static String PIC_APP_SERVER_URL="http://127.0.0.1:8383/images/editor/";
  public static String PIC_APP_FILE_SYSTEM_CKEDITOR_LOCATION="D:/images/editor";
  public static final int SUCCESS = 1; // 操作成功
  public static final int FAILED = 2; // 操作shibai
}
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
  /*  registry.addResourceHandler("swagger-ui.html")
        .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
    registry.addResourceHandler("/webjars/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/");
    registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/static/", "classpath:/resources/", "file:./src/main/resources/static/"); */
    registry.addResourceHandler("/images/**").addResourceLocations("file:D://images/");
  }

4、最终效果

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值