spring boot集成 ueditor(guns框架)

spring boot集成 ueditor

参考:https://www.jianshu.com/p/006e65711de0
UEditor-1.4.3.3 JSP版本 http://download.csdn.net/download/weixin_35928208/10219451

图片上传返回实体

public class Ueditor {
    private String state="SUCCESS";
    private String url;
    private String title="1465731377326075274.jpg";
    private String original="80px - \\u526f\\u672c (2).jpg";
    private String size="13252";
    private String type=".jpg";

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getOriginal() {
        return original;
    }

    public void setOriginal(String original) {
        this.original = original;
    }
}

controller

@Controller
public class UeditorController {
    @RequestMapping(value="/ueditor")
    @ResponseBody
    public Object ueditor(HttpServletRequest request) {
        String classPathFile = ResKit.getClassPathFile("config.json");
        byte[] bytes = FileUtil.toByteArray(classPathFile);
        String s = new String(bytes);
        Object parse = JSON.parse(s);
        return parse;
    }
    @RequestMapping(value="/imgUpload")
    @ResponseBody
    public Ueditor imgUpload(MultipartFile upfile){
        return UploadUtil.upload(upfile);
    }

}

后台返回到前台的配置文件

{
    "imageActionName": "uploadimage",
    "imageFieldName": "upfile",
    "imageMaxSize": 2048000,
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
    "imageCompressEnable": true,
    "imageCompressBorder": 1600,
    "imageInsertAlign": "none",
    "imageUrlPrefix": "",
    "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",

    "scrawlActionName": "uploadscrawl",
    "scrawlFieldName": "upfile",
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "scrawlMaxSize": 2048000,
    "scrawlUrlPrefix": "",
    "scrawlInsertAlign": "none",

    "snapscreenActionName": "uploadimage",
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "snapscreenUrlPrefix": "",
    "snapscreenInsertAlign": "none",


    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage",
    "catcherFieldName": "source",
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "catcherUrlPrefix": "",
    "catcherMaxSize": 2048000,
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],

    "videoActionName": "uploadvideo",
    "videoFieldName": "upfile",
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}",
    "videoUrlPrefix": "",
    "videoMaxSize": 102400000,
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"],

    "fileActionName": "uploadfile",
    "fileFieldName": "upfile",
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",
    "fileUrlPrefix": "",
    "fileMaxSize": 51200000,
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ],
    "imageManagerActionName": "listimage",
    "imageManagerListPath": "/ueditor/jsp/upload/image/",
    "imageManagerListSize": 20,
    "imageManagerUrlPrefix": "",
    "imageManagerInsertAlign": "none",
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],

    "fileManagerActionName": "listfile",
    "fileManagerListPath": "/ueditor/jsp/upload/file/",
    "fileManagerUrlPrefix": "",
    "fileManagerListSize": 20,
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ]

}

修改ueditor.config.js文件 (拉取配置文件)

serverUrl: Feng.ctxPath+"/ueditor"

引入js

    <script type="text/javascript" charset="utf-8" src="${ctxPath}/static/js/plugins/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="${ctxPath}/static/js/plugins/ueditor/ueditor.all.js"> </script>
    <script type="text/javascript" charset="utf-8" src="${ctxPath}/static/js/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>

添加js 修改图片上传位置

    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
            return Feng.ctxPath+'/imgUpload';
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }

最终使用

<script id="editor" type="text/plain" style="width:1024px;height:500px;"></script> //html body中
var ue = UE.getEditor('editor'); //js中

pom jar包

        <!--UEditor依赖的jar包 -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
我的业务 (参考)

上传 (对接图片接口)

public class UploadUtil {

    public static Ueditor upload(MultipartFile upfile) {
        Ueditor ueditor = new Ueditor();
        ueditor.setOriginal(upfile.getOriginalFilename());
        ueditor.setSize(String.valueOf(upfile.getSize()));
        ueditor.setType(upfile.getContentType());
        ueditor.setTitle(upfile.getName());
        HashMap<String, byte[]> byteMap = new HashMap<>();
        byte[] buff = new byte[0];
        try {
            buff = upfile.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byteMap.put("File", buff);

        String token = TokenUtil.getToken(Const.TOKEN_TYPE_UPLOAD);
        HashMap<String, String> map = new HashMap<String, String>() {{
            put("postName", "ueditor");
            put("token", token);
            put("clientId", TokenUtil.CLIENT_ID);
        }};
        String phoneToken = null;
        String url = "";
        try {
            phoneToken = UploadUtil.post("http://xa-app.youedata.com/pub/upload?", map, byteMap);
            String[] files = phoneToken.split("\"File\":\"");
            String[] split = files[1].split("\"}}");
            url = split[0];
        } catch (Exception e) {
            ueditor.setState("上传失败");
            e.printStackTrace();
        }
        if(token==null){
            ueditor.setState("Token获取失败");
        }
        ueditor.setUrl(url);
        return ueditor;
    }

    private static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }

    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }

    private static String boundaryString = getBoundary();

    private static String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    private static String post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(30000);
        conne.setReadTimeout(50000);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if (fileMap != null && fileMap.size() > 0) {
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) {
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode("File") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try {
            if (code == 200) {
                ins = conne.getInputStream();
            } else {
                ins = conne.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new String(new byte[0]);
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return new String(bytes);
    }


}

获取token

public class TokenUtil {

    public static final String CLIENT_SECRET_KEY = "e1c507cbe8fa4f03a2252e8e14c38783";
    public static final String CLIENT_ID = "e1c507cbe8fa4f03a2252e8e14c38782";
    public static final String TIMESTAMP = String.valueOf(new Date().getTime() / 1000);
    public static final String SEQ = TIMESTAMP.substring(TIMESTAMP.length() - 8);

    public static String getToken(String tokenType) {
        HashMap<String, String[]> treemap = new HashMap<String, String[]>(){{
            put("clientId", new String []{CLIENT_ID});
            put("type", new String []{tokenType});
            put("timestamp", new String []{TIMESTAMP});
            put("seq", new String []{SEQ});
//            put("clientSecret", new String []{CLIENT_SECRET_KEY});
        }};
        String sign = SignUtil.getSign(CLIENT_SECRET_KEY, treemap);
        Map<String, String> map = new HashMap<String, String>(){{
            put("clientId", CLIENT_ID);
            put("type", tokenType);
            put("timestamp", TIMESTAMP);
            put("seq", SEQ);
            put("sign", sign);
        }};
        String tokenString = HttpKit.sendGet("http://xa-app.youedata.com/pub/token", map);
        Map<String, String> token = (Map<String, String>) JSON.parse(tokenString);
        System.out.println("Token:"+token.get("token"));
        return token.get("token");
    }

    public static String sendSms(String phone,String token) {
        System.out.println(token);
        Map<String, String> map = new HashMap<String, String>() {{
            put("clientId", TokenUtil.CLIENT_ID);
            put("phone", phone);
            put("token",token );
        }};
        String phoneToken = HttpKit.sendGet("http://xa-app.youedata.com/pub/smscode", map);
        return phoneToken;
    }

    public static String getResult(String phone, String code,String token) {
        Map<String, String> map = new HashMap<String, String>() {{
            put("clientId", CLIENT_ID);
            put("phone", phone);
            put("token", token);
            put("code", code);
        }};
        String checkPhoneToken = HttpKit.sendGet("http://xa-app.youedata.com/pub/checksmscode", map);
        return checkPhoneToken;
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值