副文本編輯器 KindEditor 實現圖片上傳到騰訊雲對象存儲 COS

目錄

 

一、主要功能實現

二、效果圖

三、需要導入的包

四、前端編程

五、後臺編程

六、github 下載

附加內容:


一、主要功能實現

1、配置 KindEditor 

2、在 KindEditor 中實現圖片上傳

3、將圖片上傳到騰訊對象存儲 COS 上

二、效果圖

三、需要導入的包

<!-- JSONObject 需要導入的包 -->
<dependency>
    <groupId>org.apache.clerezza.ext</groupId>
    <artifactId>org.json.simple</artifactId>
    <version>0.4</version>
</dependency>

<!-- 文件上傳 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>

<!-- 騰訊雲COS 需要依賴的 jar 包 -->
<dependency>
    <groupId>com.qcloud</groupId>
    <artifactId>cos_api</artifactId>
    <version>5.2.4</version>
</dependency>

四、前端編程

在編寫代碼之前,我們需要在 index.jsp 中先引入一些 kindeditor 自己封裝好的 js 文件,同時還要引入 jquery.js 文件。這些文件我放項目工程中,可以從 github 上下載項目源碼後,從裏面複製出來,具體位置如下圖,在 webapp 下面。github 下載地址在博客最後給出。

引入的 css 和 js 文件:(注意根據自己的實際存放路徑修改)

<link rel="stylesheet" href="${pageContext.request.contextPath}/static/kindeditor/themes/default/default.css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/kindeditor/plugins/code/prettify.css" />
<script charset="utf-8" src="${pageContext.request.contextPath}/static/kindeditor/kindeditor-all.js"></script>
<script charset="utf-8" src="${pageContext.request.contextPath}/static/kindeditor/lang/zh-CN.js"></script>
<script charset="utf-8" src="${pageContext.request.contextPath}/static/kindeditor/plugins/code/prettify.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.js"></script>

body 的內容: (js 代碼中的 cssPath 參數值也需要根據實際的路徑進行修改)

<body>
<form method="post" action="upload" name="myform" enctype="multipart/form-data">
    <textarea type="text" name="uploadImage" style="height:600px;width:80%;" value=""></textarea>
    <button type="submit">提交</button>	
</form>

<script>
    //加載KindEditor插件
    KindEditor.ready(function(K) {
        var KE = K.create('textarea[name="uploadImage"]', {
            cssPath : 'static/kindeditor/plugins/code/prettify.css',
            filePostName  : "file",
            uploadJson : 'kindEditorUpload',
            allowFileManager : false,
            allowImageUpload: true, //上傳圖片框本地上傳的功能,false爲隱藏,默認爲true
            allowImageRemote : false, //上傳圖片框網絡圖片的功能,false爲隱藏,默認爲true
            formatUploadUrl:false,
            resizeType: 0,
            afterCreate : function() {
                var self = this;
                this.sync();
                K.ctrl(document, 13, function() {
                    self.sync();
                    document.forms['myform'].submit();//獲取表單的 name 值
                });
                K.ctrl(self.edit.doc, 13, function() {
                    self.sync();
                    document.forms['myform'].submit();
                });
            },
            afterBlur:function() { this.sync(); }, 	//失去焦點後,將內容寫入textarea中
            afterUpload:function(url,data,name){
                if( name=="image" || name == "multiimagez"){
                    var img = new Image();
                    img.src = url;
                    img.onload = function(){
                        if( img.width > 600 ){
                            //當圖片的寬度大於 600px 的時候,就將圖片的寬度縮放爲 600px
                            KE.html(KE.html().replace('<img src="' + url + '"','<img src="' + url + '" width="600"'));
                        }else if( img.width == img.height ){
                            //當圖片的寬度和高度一樣時候,就將圖片的大小縮放爲 200px
                            KE.html(KE.html().replace('<img src="' + url + '"','<img src="' + url + '" width="200"'));
                        }
                    }
                } 
            }
        });
        prettyPrint();
    });
</script>
</body>

五、後臺編程

1、配置騰訊雲COS對象存儲常量

新建一個 com.utils 包,在包裏新建一個 COSConfig.java 類,是用來存放一些COS的常量信息。

(關於騰訊雲COS如何創建對象存儲並獲取這些變量,請參考博客最後的附加內容)

package com.utils;

//騰訊雲COS對象存儲常量
public class COSConfig {
	    
    //secretId
    public static final String SECRETID = "AKIDfO0Zz*************************";
    
    //secretKey
    public static final String SECRETKEY = "b1Jzp9Y****************************";
    
    //bucket的區域, COS地域的簡稱請參照 https://www.qcloud.com/document/product/436/6224
    public static final String REGION = "ap-guangzhou";
    
    // bucket名需包含appid
    public static final String BUCKETNAME = "hstc-image-125********";
    
}

再新建一個 DateConvent.java 類,是用來把 Date 類型轉爲 String 的。 

package com.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

//轉換時間的工具類
public class DateConvert {
	
	public String toString(Date date) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String time = simpleDateFormat.format(date);
		return time;
	}

}

2、Controller 層的實現

新建一個 KindEditorController.java 類。

代碼並不需要大量的修改,只需要根據代碼後面的注意或提示進行部分參數和鏈接的修改就行。

package com.controller;

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

import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import com.utils.COSConfig;
import com.utils.DateConvert;

@Controller
public class KindEditorController {
	/**
	 * 副文本編輯框的內容獲取
	 * 獲取表單的信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/upload",produces="application/json;charset=utf-8")
	@ResponseBody
	public String upload(HttpServletRequest request){
		String context = request.getParameter("uploadImage");
		System.out.println("打印的內容爲:"+context);
		return "1111";
	}
	
	/**
	 * 副文本編輯框中的圖片上傳功能
	 * @param file
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value="/kindEditorUpload")//與 副文本編輯框中的 uploadJson 參數對應
	@ResponseBody
	public String uploadSingleImage(MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
		String contentType = file.getContentType();
		InputStream inputStream = file.getInputStream();
		long size = file.getSize();
		if(size != 0) {
			 // 初始化用戶身份信息(secretId, secretKey)
	        COSCredentials cred = new BasicCOSCredentials(COSConfig.SECRETID, COSConfig.SECRETKEY);
	        // 設置bucket的區域, COS地域的簡稱請參照 https://www.qcloud.com/document/product/436/6224
	        ClientConfig clientConfig = new ClientConfig(new Region(COSConfig.REGION));
	        // 生成cos客戶端
	        COSClient cosclient = new COSClient(cred, clientConfig);
	        // bucket名需包含appid
	        String bucketName = COSConfig.BUCKETNAME;
	        
	        //獲取後綴名
	        String[] split = contentType.split("/");
	        //文件名
	        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
	        
	        //當前日期
	        Date date = new Date();
	        DateConvert util = new DateConvert();
	        String dd = util.toString(date);
	        
	        //目標文件名
	        String key = "/" + dd + "/" + uuid + "." + split[1];
	        
	        ObjectMetadata objectMetadata = new ObjectMetadata();
	        // 從輸入流上傳必須制定content length, 否則http客戶端可能會緩存所有數據,存在內存OOM的情況
	        objectMetadata.setContentLength(size);
	        // 默認下載時根據cos路徑key的後綴返回響應的contenttype, 上傳時設置contenttype會覆蓋默認值
	        objectMetadata.setContentType(contentType);
	        
	        PutObjectRequest putObjectRequest =
	                new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
	        // 設置存儲類型, 默認是標準(Standard), 低頻(standard_ia), 近線(nearline) 
	        putObjectRequest.setStorageClass(StorageClass.Standard);
	        try {
	            cosclient.putObject(putObjectRequest);
	        } catch (CosServiceException e) {
	            e.printStackTrace();
	        } catch (CosClientException e) {
	            e.printStackTrace();
	        }
	        
	        // 關閉客戶端        
	        cosclient.shutdown(); 
	        JSONObject obj = new JSONObject();
			obj.put("error", 0);
			obj.put("url", "https://hstc-image-125*****.cos.ap-guangzhou.myqcloud.com" + key);
			return obj.toJSONString();
		} else {
			return getError("上傳失敗");
		}
	}
	/**
	 * 沒有上傳成功時候返回的參數
	 * @param message
	 * @return
	 */
	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
}

注意:

1、前後臺路徑要一樣

kindeditor 的初始化 js 代碼中的屬性 uploadJson 的值應該爲後臺上傳的圖片的路由(@RequestMapping(valeu="")),而屬性 filePostName 的值“file”要對應上上傳圖片的類的參數名()。

2、騰訊雲圖片的 url 

返回的圖片返回鏈接需要自己拼接,https 這一段需要換成自己騰訊雲 COS 中的鏈接,至於怎麼獲取請博客最後的附加內容。

六、github 下載

https://github.com/yyzheng1729/kindeditor

附加內容:

1、進入自己騰訊雲服務器的控制檯,打開對象存儲。

2、創建存儲桶

3、填寫存儲桶相關信息

4、查看基本配置

5、SECRETID 和 SECRETKEY 的獲取

https://console.qcloud.com/cam/capi

打開上面的鏈接,登錄進去,就能找到了,如下圖:

如果第一次沒有,就自己新建一個密鑰。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章