spring集成百度编辑器

本文介绍了如何在项目中集成百度编辑器,并详细说明了所需依赖文件及配置过程。包括如何处理图片上传、远程图片抓取等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近期接到工作任务,在线hmtl5技术预演,将文字或图片生成html文件作为培训课件供app用户参与考试,想到了百度编辑器,于是乎就引入了百度编辑器功能。

先说下依赖文件:

js模块

<link rel="stylesheet" href="/plugins/ueditor/themes/default/css/ueditor.css" >
<script type="text/javascript" src="/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<script type="text/javascript" src="/plugins/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="/plugins/ueditor/ueditor.all.js"></script>

资源文件:

{
    "imageActionName": "uploadimage",
    "imageFieldName": "upfile", 
    "imageMaxSize": 2048000, 
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp",".PNG"],
    "imageCompressEnable": true, 
    "imageCompressBorder": 1600,
    "imageInsertAlign": "none", 
    "imageUrlPrefix": "",
    "imagePathFormat": "{yyyy}{mm}{dd}_{time}_{rand:6}" ,
    
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", 
    "catcherFieldName": "source", 
    "catcherPathFormat": "{yyyy}{mm}{dd}_{time}_{rand:6}", 
    "catcherUrlPrefix": "",
    "catcherMaxSize": 2048000, 
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp",".PNG"]
}

spring引入百度编辑器-控制器

/* 
 * Copyright (c) 2016, S.F. Express Inc. All rights reserved.
 */
package com.sf.sgs.ops.web.controller.apk;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sf.framework.utils.DateFormatUtils;
import com.sf.sgs.ops.utils.conf.CommonUtils;

/**
 * 描述:百度编辑器配置
 * 
 * @author 01223831
 * @since 1.0
 */
@RequestMapping("/ueditor")
@Controller
public class UeditorConfigController {
    
    Logger logger = Logger.getLogger(UeditorConfigController.class);
    
    @Autowired
    private CommonUtils commonUtils;
    
    @RequestMapping(value = "/exec")
    public void exec(String action, HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8"); 
        response.setContentType("application/json;charset=UTF-8");
        if("config".equals(action)){
            try {
                this.getUeditorConfig(request, response);
            } catch (Exception e) {
                logger.error("获取ueditor配置文件失败," , e);
            }
        } else if("uploadimage".equals(action)){
            Map<String, String> resultMap = this.uploadImage(request);
            try {
                response.getWriter().write(JSON.toJSONString(resultMap));
            } catch (IOException e) {
                logger.error("上传图片失败," , e);
            }
        } else if("catchimage".equals(action)){
           Map<String, String[]> paramMap = request.getParameterMap();
           String[] catchImgs = paramMap.get("source[]");
           
           Map<String, Object> resultMap = this.catchImgs(catchImgs);
           try {
               response.getWriter().write(JSON.toJSONString(resultMap));
           } catch (IOException e) {
               logger.error("抓取远程图片失败," , e);
           }
        }
    }
    
    /**
     * 读取百度编辑器配置
     * @param action
     * @param request
     * @param response
     * void
     */
    private void getUeditorConfig(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //String filename = Thread.currentThread().getContextClassLoader().getResource("/").getPath() + "plugins/ueditor/jsp/ueditor.json";
        File cfgFile = ResourceUtils.getFile("classpath:ueditor.json"); 
        logger.info("UEditor ueditor.json filePath:"+cfgFile.getName());
        String configStr;
        try {
            configStr = FileUtils.readFileToString(cfgFile);
            logger.info("UEditor ueditor.json " + configStr);
            response.getWriter().write(configStr);
        } catch (IOException e) {
            logger.error("读取Ueditor配置文件错误," , e);
        }
    }
    
    /**
     * 上传图片
     * @param request
     */
    private Map<String, String> uploadImage(HttpServletRequest request){
        
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
        MultipartFile uploadFile = multiRequest.getFile("upfile");
        Map<String, String> resultMap = new HashMap<String, String>();
        if (uploadFile == null){
            resultMap.put("state", "图片不存在!");
            return resultMap;
        }
        try {
            UeditorConfig ueditorConfig = this.getUeditorConfigBean(request);
            if (ueditorConfig == null){
                logger.error("读取ueditor.json配置文件错误");
                resultMap.put("state", "读取配置失败");
                return resultMap;
            }
            Long size = uploadFile.getSize();
            String originFileName = uploadFile.getOriginalFilename();
            if (originFileName == null){
                originFileName = "";
            }
          
            //文件大小限制
            if (size > ueditorConfig.getImageMaxSize()){
                resultMap.put("state", "文件大小超过最大限制" + ueditorConfig.getImageMaxSize() + "B");
                return resultMap;
            }
            
            //文件格式限制
            String suffix = StringUtils.substringAfterLast(originFileName, ".");
            
            if (!ueditorConfig.getImageAllowFiles().contains("."+suffix)) {
                resultMap.put("state", "文件格式"+suffix+"不支持!");
                return resultMap;
            }
            
            //保存文件
            String savePath = commonUtils.getImageStorePath();
            File savePathFile = new File(savePath);
            if(!savePathFile.exists()){
                savePathFile.mkdirs();
            }
            String rand6 = RandomStringUtils.random(6, "abcdefghijklmnopqrstuvwxyz");
            String fileName = DateFormatUtils.format(new Date(), "yyyyMMdd_HHmmss_") + rand6 + "." + suffix ;
            String filePath = savePath + fileName ;
            //String url = "/ops/parse/getImage?suffix="+ fileName;
            String url = commonUtils.getSgsNasReflectUrl()+ File.separator + fileName;
            uploadFile.transferTo(new File(filePath));
            resultMap.put("state", "SUCCESS");
            resultMap.put("url", url);
            resultMap.put("type", suffix);
            resultMap.put("original", originFileName);
            return resultMap;
        } catch (IOException e) {
            logger.error("读取Ueditor配置文件错误," , e);
            resultMap.put("state", "上传图片失败");
            return resultMap;
        }
    }
    private UeditorConfig getUeditorConfigBean(HttpServletRequest request) throws IOException {
        
        File cfgFile = ResourceUtils.getFile("classpath:ueditor.json"); 
        logger.info("parse UEditor ueditor.json filePath:"+cfgFile.getName());
        String configStr = FileUtils.readFileToString(cfgFile);
        JSONObject jsonObject = JSON.parseObject(configStr);
        UeditorConfig ueditorConfig = (UeditorConfig)JSON.toJavaObject(jsonObject, UeditorConfig.class);
        return ueditorConfig;
    }
    
    /**
     * 抓取远程图片
     * @param catchImgs
     * @return
     * Map<String,Object>
     */
    private Map<String, Object> catchImgs(String[] catchImgs) {
        
       Map<String, Object> resultMap = new HashMap<>();
       if(catchImgs == null){
           resultMap.put("state", "SUCCESS");
           return resultMap;
       }
       List<Map<String, String>> list = new ArrayList<>();
       if(catchImgs!=null && catchImgs.length>0) {
           for(String source:catchImgs){
               String nSrc = this.catchImg(source);
               Map<String, String> item = new HashMap<>();
               item.put("url", nSrc);
               item.put("source", source);
               item.put("state", "SUCCESS");
               list.add(item);
           }
       }
       resultMap.put("state", "SUCCESS");
       resultMap.put("list", list);
       return resultMap;
    }
    
    /**
     * 下载图片,并且返回新的图片地址
     * @param src   图片原地址
     * @return      新的图片地址
     */
    private String catchImg(String src) {
        
        String[] supportImageType = new String[]{".png", ".jpg", ".jpeg", ".gif", ".bmp"};
        String rand6 = RandomStringUtils.random(6, "abcdefghijklmnopqrstuvwxyz");
        String fileName = DateFormatUtils.format(new Date(), "yyyyMMdd_HHmmss_") + rand6;
        if(StringUtils.endsWithAny(src, supportImageType)){
            String suffix = StringUtils.substringAfterLast(src, ".");
            fileName = fileName + "." + suffix;
        } else {
            fileName = fileName + ".jpg.jpg";
        }
        FileOutputStream output = null;
        try {
            HttpClient client = new HttpClient();  
            GetMethod get = new GetMethod(src);  
            client.executeMethod(get);  
            
            String imageStorePath = commonUtils.getImageStorePath();
            File filePath = new File(imageStorePath);
            File storeFile = new File(filePath, fileName);
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            output = new FileOutputStream(storeFile);  
            output.write(get.getResponseBody());  
            output.close();  
            String url = "/ops/parse/getImage?suffix="+fileName;
            return url;
        }catch(Exception e) {
            e.printStackTrace();
        }finally{
            if (output!=null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return src;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值