Bootstrap

CKEditor上传图片

CKEditor作为老牌开源的优秀在线编辑器,一直受到开发者的青睐,由于CKFinder的图片上传和视频上传要收费,所以没有采用其ckfinder搭配使用。这里我们讲解下 ckeditor最新版本4.8的图片上传配置。 https://ckeditor.com/download

1.开启图片上传界面

文件地址:ckeditor/plugins/image/dialogs/image.js

搜索"Upload",将

        id:"Upload",hidden:!0

改为:

    id:"Upload",hidden:false

2.配置上传图片路径

第一种方式:

官方文档在ckeditor的config.js里面加入:config.filebrowserUploadUrl ='',这里不推荐使用这种方法,

这样配置不方便,因为我们表单的传送地址一般是动态生成,直接在js文件里面写入静态的地址不利于维护。

这里使用jsp页面传输路径:

首先打开文件ckeditor/ckeditor.js,把

    f=a.config.filebrowserUploadUrl

改为

f=filebrowserUploadUrl

 接着在jsp页面引入ckeditor.js之前声明变量filebrowserUploadUrl并赋值。

<script type="text/javascript">
    var filebrowserUploadUrl =  baseUrl+'/CKEditor/imageUpload';
</script>
<script src="${base}/resources/common/plugins/ckeditor/ckeditor.js"></script>

第二种方式:

需要在ckeditor中config.js文件中配置上传图片方法的路径,至于查看图片的方法,在上传成功后返回给页面端了就不需要配置了。

CKEDITOR.editorConfig = function( config ) {
    config.language = 'zh-cn'; //配置语言
    config.width = 850; //宽度
    config.resize_enabled = true;// 取消 “拖拽以改变尺寸”功能
    config.toolbar = "Full";// full-全能工具栏;basic-基础工具栏;
    config.uiColor = '#0fbabb';
    //工具栏的配置
    config.toolbar= [
        ['Source'],
        ['Templates','Cut ','Copy ','Paste','PasteText','SelectAll','RemoveFormat'],
        ["SpellChecker","Undo","Redo","Find","Replace"],
        ["Bold","Italic","Underline","Strike","Outdent","Indent"],
        ['Form','Checkbox','Radio','TextField','Textarea','Select ','Button','ImageButton'],
        ["NumberedLisst","BulletedList","-","JustifyLeft","JustifyCenter","JustifyRight","JustfyBlock"],
        ["Image","Flash","Table","Link","Unlink","Anchor","Smiley","SpecialChar"],
        ["Styles","Format","Font","FontSize"],
        ["TextColor","BGColor"],
        ["Maximize"]
    ];
    config.filebrowserImageUploadUrl = '/CKEditor/image';
    config.filebrowserFlashUploadUrl = "/CKEditor/video";
};

接着修改jsp页面数据替换配置中的链接生成动态的路径:

<script>
    CKEDITOR.replace('ckeditor',{
        filebrowserImageUploadUrl : baseUrl+"/CKEditor/image",
        filebrowserFlashUploadUrl : baseUrl+"/CKEditor/video",
    });
</script>

以上就是ckeditor的简单上传图片配置。

下面介绍后台使用的步骤:

1.controller层接收ckeditor的请求

@Controller
@RequestMapping(value = "/CKEditor")
public class CKEditorController extends BaseController {

    /**
     * ckeditor图片上传
     *
     * @Title imageUpload
     * @param request
     * @param response
     */
    @RequestMapping("imageUpload")
    public void imageUpload(HttpServletRequest request, HttpServletResponse response) {
        try {
            CKImageUploadUtil.ckeditor(request, response);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

接下来使用工具类上传图片到本地:

/**
 * @ClassName: CKImageUploadUtil
 * @Description: 图片上传工具类,包括CKEditor操作
 */
public class CKImageUploadUtil {
    private static final Log logger = LogFactory.getLog(CKImageUploadUtil.class);

    // 图片类型
    private static List<String> fileTypes = new ArrayList<String>();

    static {
        fileTypes.add(".jpg");
        fileTypes.add(".jpeg");
        fileTypes.add(".bmp");
        fileTypes.add(".gif");
        fileTypes.add(".png");
    }

    /**
     * 图片上传
     *
     * @Title upload
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public static String upload(HttpServletRequest request) throws IllegalStateException,
            IOException {
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
                .getServletContext());
        // 图片名称
        String fileName = null;
        // 判断 request 是否有文件上传,即多部分请求
        try {
            if (multipartResolver.isMultipart(request)) {
                // 转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 记录上传过程起始时的时间,用来计算上传时间
                    // int pre = (int) System.currentTimeMillis();
                    // 取得上传文件
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if (file != null) {
                        // 取得当前上传文件的文件名称
                        String myFileName = file.getOriginalFilename();
                        // 如果名称不为'',说明该文件存在,否则说明该文件不存在
                        if (myFileName.trim() != "") {
                            // 获得图片的原始名称
                            String originalFilename = file.getOriginalFilename();
                            // 获得图片后缀名称,如果后缀不为图片格式,则不上传
                            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                            if (!fileTypes.contains(suffix)) {
                                continue;
                            }
                            //不使用原始文件名
                            fileName = Property.FILE_IMAG_UPLOADPATH +"/"+ DateUtil.getDateString()+ "/"+  BCryptUtil.randomUUID() + ".jpg";
                            File uploadFile = new File(Property.FILE_UPLOAD_ROOTPATH + Constants.separator+  fileName);
                            if(!uploadFile.getParentFile().exists()) {
                                if(!uploadFile.getParentFile().mkdirs()) {
                                    logger.error("create directory failed, {}"+uploadFile.getPath());
                                    fileName = StringUtil.EMPTY;
                                    ErrorCode.UPLOAD_IMAGE_FAILED.issue();
                                }
                            }
                            file.transferTo(uploadFile);
                        }
                    }
                }
            }
        }catch (Exception e) {
            logger.error("upload file failed ", e);
            fileName = StringUtil.EMPTY;
            ErrorCode.UPLOAD_IMAGE_FAILED.issue();
        }finally {
            return fileName;
        }
    }

    /**
     * ckeditor文件上传功能,回调,传回图片路径,实现预览效果。
     *
     * @Title ckeditor
     * @param request
     * @param response
     * @throws IOException
     */
    public static void ckeditor(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String fileName = upload(request);
        String callback = request.getParameter("CKEditorFuncNum");
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        out.println("<script type=\"text/javascript\">");
        if(StringUtil.isNotEmpty(fileName)){
            // 结合ckeditor功能
            String imageContextPath = Property.FILE_UPLOAD_ROOTURL + fileName;
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imageContextPath + "',''" + ")");

        }else{
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'图片上传失败");
        }
        out.println("</script>");
        out.flush();
        out.close();
    }
}

;