1. 程式人生 > >配合七牛雲簡易使用kindeditor編輯器的圖片上傳功能

配合七牛雲簡易使用kindeditor編輯器的圖片上傳功能

專案中使用到kindeditor富文字編輯器,專案後端用的springboot框架,圖片伺服器用的是七牛雲。簡單介紹一下如何將kindeditor編輯器的圖片上傳功能與七牛結合起來用。

一、kindeditor配置

將kindeditor引入到專案中是很簡單的,官網就有很清楚的demo,就不贅述了,需要說一下的就是kindeditor的初始化配置

KindEditor.ready(function (K) {
        window.editor = K.create('#editor_id', {
            height: '600px',
            themeType: 'default'
, allowPreviewEmoticons: false, allowImageUpload: true, allowFileManager: true, uploadJson: '/operation/news/uploadImage.do', afterUpload: function () { this.sync() }, items: [ 'source', '|'
, 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'link', 'unlink', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen','/', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold','italic', 'underline', 'strikethrough', 'lineheight', 'removeformat','|'
, 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript','superscript' ] }); });

這裡uploadJson引數我填的是專案中圖片上傳controller的mapping地址,其餘初始化引數的配置請參考kindeditor的官方文件http://kindeditor.net/docs/option.html#id113

二、後臺實現圖片上傳

    @ResponseBody
    @PostMapping("/uploadImage.do")
    public Map<String, Object> uploadImage(@RequestParam(required = false) MultipartFile imgFile) {
        try {
             Map<String, Object> succMap = new HashMap<>();
            String imgUrl = QiniuUtil.uploadFile(imgFile.getInputStream());
            succMap.put("error", 0);
            succMap.put("url", imgUrl);
            return succMap;
        } catch (Exception e){
            Map<String, Object> msg = new HashMap<String, Object>();
            msg.put("error", 1);
            msg.put("message", "<font size='3'>您選擇的檔案上傳失敗!</font>");
            return msg;
        }
    }

七牛上傳檔案參考其官方api,是很方便的,配置好accessKey、secretKey、bucket、domain即可
這是我封裝在QiniuUtil裡的檔案上傳方法

    // 上傳檔案並返回檔案的url
    public static String uploadFile(InputStream in) {
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        DefaultPutRet putRet = null;
        try {
            //這裡不傳key,雲端用hash值作為檔名
            Response response = uploadManager.put(in, null, upToken, null, null);
            // 解析上傳成功的結果
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            LOGGER.debug("上傳成功,key:{},hash:{}", putRet.key, putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            LOGGER.debug("上傳出錯,{}" + r.toString());
        }
        return domain + putRet.key;
    }

這裡需要注意的是圖片檔案的引數名需要定義為imgFile,否則controller將接收不到圖片檔案(不要問我怎麼知道的,說多了都是淚T_T)。