富文本编辑器kindeditor4.1.11,官网下载后文件目录如下(我这里只保留了java语言开发的jsp包)
将类库放在项目中后就可以开始使用了,以下使用过程中取用路径请自行甄别,如果已经会调用,只想看代码迁移方法请跳转步骤四
步骤一:
在jsp页面中引入类库:
<html>
<head>
<script language="javascript" src="${jsPath}/common/kindeditor4.1.11/kindeditor-all.js"></script>
<script language="javascript" src="${jsPath}/common/kindeditor4.1.11/lang/zh-CN.js"></script>
</head>
<body>
</body>
</html>
步骤二:
在需要使用富文本框的地方插入标签<textarea></textarea>
<table style="width:765px;">
<tr>
<td style="width: 80px;">题目:</td>
<td>
<textarea name="contentT" id="contentT" style="width:80%; height: 400px;" placeholder="请输入题目" required>
</textarea>
</td>
</tr>
<tr style="margin-top: 10px;">
<td style="width: 80px;">答案:</td>
<td style="padding-right: 7px;">
<input type="text" name="right_keyT" id="right_keyT" style="width:80%; font-family:'微软雅黑';font-size: 14px;" placeholder="请输入答案" required/>
</td>
</tr>
</table>
步骤三:
在js中定义富文本属性
/** 富文本编辑框 */
var editor1;
var options = {
resizeType: 0,//2时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动。
cssPath : webPath + '/static/scripts/common/kindeditor4.1.11/plugins/code/prettify.css',//指定编辑器iframe document的CSS文件
//此处是示例代码中默认的跳转服务器程序,该代码是在jsp中写入的,我们随后要迁移的就是此处指向的文件的代码,同时也要修改这里的指向路径
uploadJson : webPath + '/static/scripts/common/kindeditor4.1.11/jsp/upload_json.jsp',//指定上传图片的服务器端程序
fileManagerJson : webPath + '/static/scripts/common/kindeditor4.1.11/jsp/file_manager_json.jsp',//指定浏览远程图片的服务器端程序。
allowImageRemote: false,//是否显示网络图片标签
filterMode: false,//过滤html代码,false时允许输入任何代码
items:[//定义功能按钮
'fontname', 'fontsize', '|',
'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', '|',
'image'
],
//设置编辑器创建后执行的回调函数。
afterCreate : function() {
var self = this;
self.sync();
},
//编辑器失去焦点(blur)时执行的回调函数。
afterBlur : function() {
var self = this;
self.sync();
}
}
function createTextarea(){
KindEditor.ready(function(K) {
editor1 = K.create('textarea[name="contentT"]', options);
})
}
配置好富文本框属性后,只要在页面初始化时js调用即可
$(function(){
//其他...
createTextarea();
//...
});
到这里就可以看下效果了:
另外需注意,因为配置中的“uploadJson:”指向的是默认的upload_json.jsp中的程序,所以在使用时要把类库中jsp/lib/目录下的三个jar包都放到tomcat下的lib目录下
步骤四:
为了代码安全性以及添加一些自己的处理程序,或者不想麻烦的再copy lib下的jar包,我们要把服务器上传程序挪到后台,另外自带的模板中的存储路径是在tomcat中项目的部署路径下新建了attached文件夹来存储上传的文件的,这样如果再次war包发版时就会将文件夹覆盖导致文件丢失,因此也需要把存储路径也给指向到其他地方。
首先变更文件上传服务器指向的程序路径,在js中配置信息options中修改
//uploadJson : webPath + '/static/scripts/common/kindeditor4.1.11/jsp/upload_json.jsp',//指定上传图片的服务器端程序
uploadJson : apiUrl + '/imgUrl/uploadJson.do',
然后是在对应的Controller中写入代码,下面是完整controller
package
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import .URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
<!-- 自定义的工具类 -->
import com.common.utils.JacksonUtil;
import com.common.utils.PropertieUtil;
import com.web.controller.BaseController;
@Scope("prototype")
@Controller
@RequestMapping("imgUrl")
public class GetAnswerImgController extends BaseController {
@RequestMapping("getAnswerImg")
@ResponseBody
public void getAnswerImg (HttpServletRequest request, HttpServletResponse response, Model model,
String basepath, String url) {
BufferedOutputStream bos = null;
InputStream fis = null;
BufferedInputStream bis = null;
PropertieUtil pu = PropertieUtil.getInstance();
Map<String,String> proMap = pu.getProperties("/main-api.properties");
String mminfoFiles = proMap.get("img.savePath");
try {
basepath = mminfoFiles;
request.setCharacterEncoding("UTF-8");
String suffix = url.substring(url.lastIndexOf(".") + 1);
suffix = suffix.toLowerCase();
response.setContentType(suffix);
url=url.trim();
String fileName = url.substring(url.lastIndexOf("/")+1);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setCharacterEncoding("UTF-8");
// if(suffix.equals("swf")){
// response.setContentType("application/" + suffix + ";charset=UTF-8");
// response.setHeader("Content-Disposition", "filename*=UTF-8''" + fileName);
// }else if(suffix.equals("pdf")){
// response.setContentType("application/" + suffix + ";charset=UTF-8");
// response.setHeader("Content-Disposition", "filename*=UTF-8''" + fileName);
// }else
if(suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("gif")){
response.setContentType("image/" + suffix + ";charset=UTF-8");
response.setHeader("Content-Disposition", "filename*=UTF-8''" + fileName);
}else{
response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName);
}
String tPath = basepath + url;
bos = new BufferedOutputStream(response.getOutputStream());
fis = new FileInputStream(tPath);
bis = new BufferedInputStream(fis);
byte[] buff = new byte[1024];
int bytesRead = 0;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))){
bos.write(buff, 0, bytesRead);
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(bos!=null){
bos.close();
}
if(bis!=null){
bis.close();
}
if(fis!=null){
fis.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("uploadJson")
@ResponseBody
public void uploadJson(HttpServletRequest request, HttpServletResponse response, MultipartFile imgFile, String dir) {
//获取配置文件参数
PropertieUtil pu = PropertieUtil.getInstance();
Map<String,String> proMap = pu.getProperties("/main-api.properties");
String saveUrl = proMap.get("img.saveUrl");//图片保存地址前缀
String savePath = proMap.get("img.savePath");//图片保存服务器地址绝对路径
//最大文件大小10M
long maxSize = Long.valueOf(proMap.get("img.maxSize"));
// 获取一个Response的Write对象
PrintWriter out = null;
try {
out = response.getWriter();
// 设置Response响应的编码
response.setContentType("text/html; charset=UTF-8");
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
if(!ServletFileUpload.isMultipartContent(request)){
out.println(getError("请选择文件。"));
return;
}
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
out.println(getError("上传目录不存在。"));
return;
}
//检查目录写权限
if(!uploadDir.canWrite()){
out.println(getError("上传目录没有写权限。"));
return;
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if(!extMap.containsKey(dirName)){
out.println(getError("目录名不正确。"));
return;
}
//创建文件夹
savePath += dirName + "/";
saveUrl += "/" + dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
String fileName = imgFile.getOriginalFilename();
long fileSize = imgFile.getSize();
if (!imgFile.isEmpty()) {
//检查文件大小
if(fileSize > maxSize){
out.println(getError("上传文件大小超过限制。"));
return;
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
File uploadedFile = new File(savePath, newFileName);
imgFile.transferTo(uploadedFile);
}catch(Exception e){
out.println(getError("上传文件失败。"));
return;
}
Map<String, Object> obj = new HashMap<String, Object>();
obj.put("error", 0);
obj.put("url", saveUrl + newFileName);
obj.put("width", "200px");//设置上传图片大小
out.println(JacksonUtil.mapToJson(obj));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
// 将writer对象中的内容输出
out.flush();
// 关闭writer对象
out.close();
}
}
@SuppressWarnings({ "unchecked", "static-access" })
private String getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj.toJSONString(obj);
}
}
步骤五:
修改后测试效果: