目录
一、主要功能实现
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
打开上面的链接,登录进去,就能找到了,如下图:
如果第一次没有,就自己新建一个密钥。