使用KindEditor富文本編譯器實現圖片上傳並回顯


前言:KindEditor富文本編譯器的格式較為嚴格,用戶必須嚴格按照文檔提供的接口規定才能實現想要的功能(本文中是在SSM環境下進行測試的)

在項目中導入如下文件

 

 

 在所需要使用該編譯器的頁面中引入

    <script src="../static/easyui/locale/easyui-lang-zh_CN.js"></script>
    <script src="../static/kindeditor/kindeditor-all.js"></script>
    <script src="../static/kindeditor/lang/zh-CN.js"></script>
    <script>
        KindEditor.ready(function (K) {
            window.editor = K.create('#editor_id',{
         // filePostName:'imgFile', //后面你就會知道這個是干啥的了 uploadJson:
'/upload', }); }); </script>

官方要求的返回格式是這樣的

 

 

 我們自己創建一個類返回固定的格式類型

public class UploadRespBean {

    private int error;
    private Object url;
    private String message;

    public UploadRespBean(int error, Object url, String message) {
        this.error = error;
        this.url = url;
        this.message = message;
    }

    public UploadRespBean() {
    }
  //省略set和get方法
}

書寫上傳類

@RequestMapping("/upload")
    public UploadRespBean upload(HttpServletRequest request, MultipartFile imgFile){
        StringBuffer url = new StringBuffer(); //存放返回url地址的容器
        String imagePath="/Hospital_Item/"+sdf.format(new Date()); //圖片的相對路徑,格式:/blogimg/日期
        String realPath = request.getServletContext().getRealPath(imagePath); //獲取項目的絕對路徑
        File imageFolder = new File(realPath); //查看是否有該文件夾

        if (!imageFolder.exists()) { //如果不存在
            imageFolder.mkdirs(); //創建該文件夾
        }
        //如果存在,將圖片的名稱重新命名
        String imageName= UUID.randomUUID()+"_"+imgFile.getOriginalFilename().replaceAll(" ", "");
        //獲取返回的url
        url.append(request.getScheme()) //相當於http
                .append("://") //相當於http://
                .append(request.getServerName()) //相當於http://localhost
                .append(":")//相當於http://localhost:
                .append(request.getServerPort())//相當於http://localhost:8080
                .append(request.getContextPath()) //獲取該tomcat容器的路徑
                .append(imagePath); //相當於http://localhost:8080/項目容器/blogimage+日期

        try {
            IOUtils.write(imgFile.getBytes(), new FileOutputStream(new File(realPath, imageName))); //存image圖片到該realPath路徑中
            url.append("/")//相當於http://localhost:8080/項目容器/blogimage+日期/
                    .append(imageName);//相當於http://localhost:8080/項目容器/blogimage+日期/圖片名稱
            return new UploadRespBean(0,url,"上傳成功!"); //上傳成功后返回圖片地址
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new UploadRespBean(1,"","上傳失敗!"); //上傳成功后返回圖片地址
    }

要特別注意MultipartFile 后面的值必須是imgFile,如果不想寫這個需要使用filePostName來自己取名字


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM