JAVA通过CKEditor文本编辑器上传图片

配置和部署我就不多做解释了,直接进入正题吧

第一步,我们要让CKEditor知道我们的上传图片的方法

找到名叫config.js的文件

JAVA通过CKEditor文本编辑器上传图片_第1张图片

加上如下配置:

CKEDITOR.editorConfig = function( config ) {
    config.image_previewText =' ';
    config.filebrowserImageUploadUrl = "/fileUpload/imageUpload";
};

第二步,在后台写上上传图片的方法,这里已JAVA为例

package com.rwj.blog.controller;

import java.io.InputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.aliyun.oss.OSSClient;
import com.rwj.blog.util.ConfigUtil;

@Controller
@RequestMapping(value="fileUpload")
public class FileUploadController {

    private static Logger logger = LoggerFactory.getLogger("logs");

    @RequestMapping(value="/imageUpload")
    public String index(
        HttpServletRequest request, 
        ModelMap model,
        @RequestParam("upload") CommonsMultipartFile file
    ) {
        try{
            if(file != null){
                  //将文件上传到阿里OSS上
                  String endpoint = ConfigUtil.getParameter("endpoint");
                  String accessKeyId = ConfigUtil.getParameter("accessKeyId");
                  String accessKeySecret = ConfigUtil.getParameter("accessKeySecret");
                  String bucketName = ConfigUtil.getParameter("bucketName");
                  String imageHeadUrl = ConfigUtil.getParameter("imageHeadUrl");
                  OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                  InputStream inputStream = file.getInputStream();
                  //获取上传后的图片地址,并且关闭OSS连接
                  String imageUrl = UUID.randomUUID().toString() + ".jpg";
                  ossClient.putObject(bucketName, imageUrl, inputStream);
                  if(ossClient != null) ossClient.shutdown();
                  if(inputStream != null) inputStream.close();
                  //将图片信息返回给CKEditor
                  String callback = request.getParameter("CKEditorFuncNum"); 
                  model.put("imageUrl", imageHeadUrl + "/" + imageUrl);
                  model.put("callback", callback);
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error("");
        }
        return "/uploadJump";
    }

}

第三步,返回一个名为uploadJump.jsp的页面给CKEditor,主要是用于预览

<script type="text/javascript">
    window.parent.CKEDITOR.tools.callFunction('${callback}','${imageUrl}','');
script>

最后上传成功!

JAVA通过CKEditor文本编辑器上传图片_第2张图片

你可能感兴趣的:(Java)