公司项目需要一个富文本框编辑功能,我就自己写了一个demo;使用eclipse/mysql/xhEditor,将图片转为二进制存到数据库中,数据库使用Blob进行存储
1、Demo结构如下,
2、本地创建SpringBoot工程引入相关的依赖;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- spring boot 相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!-- spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
3、添加相关配置application.properties;也可以使用yml进行配置,原理相同
spring.thymeleaf.prefix:classpath:/templates/
spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.tomcat.max-active=20
spring.datasource.tomcat.test-while-idle=true
spring.datasource.tomcat.validation-query=select 1
spring.datasource.tomcat.default-auto-commit=false
spring.datasource.tomcat.min-idle=15
spring.datasource.tomcat.initial-size=15
spring.data.jpa.repositories.enabled=true
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=true
spring.jpa.show-sql=true
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
4、controller代码
/**
* 本地图片上传功能:
* @param request
* @param filedata
* @return
* @throws IOException
* @throws SQLException
* @throws SerialException
*/
@RequestMapping("/xheditorImg")
@ResponseBody
public String imgUpload(@RequestParam MultipartFile filedata, String id) throws IOException, SerialException, SQLException {
byte[] bytes = filedata.getBytes();
String imageEncoder = FileUtil.getImageEncoder(bytes);
XheditorDemo xheditorDemo=new XheditorDemo();
xheditorDemo.setcId(id);
xheditorDemo.setContent(BlobUtil.StringToBlob(imageEncoder));
xheditorDemo.setAuthor("Test");
xheditorDemo.setCreateTime(new Date());
xheditorDemo.setUpdateTime(new Date());
uploadService.saveXheditorDemo(xheditorDemo);
String err = "信息";
String message = "{\"err\":\"" + err + "\",\"msg\":\"" + imageEncoder + "\"}";
err = message;
return message;
}
/**
* 网络截图上传
* @param id
* @param content
* @return
* @throws SQLException
* @throws SerialException
*/
@RequestMapping("/mainUpload")
@ResponseBody
public String mainUpload(String id,String content) throws SerialException, SQLException {
System.out.println("content="+content);
XheditorDemo xheditorDemo=new XheditorDemo();
xheditorDemo.setcId(id);
xheditorDemo.setContent(BlobUtil.StringToBlob(content));
xheditorDemo.setAuthor("Test");
xheditorDemo.setCreateTime(new Date());
xheditorDemo.setUpdateTime(new Date());
uploadService.saveXheditorDemo(xheditorDemo);
return content;
}
/**
*
* @param cId
* @return
* @throws SQLException
* @throws IOException
*/
@RequestMapping("/getXhidtor")
@ResponseBody
public String getXhidtor(String cId) throws SQLException, IOException {
XheditorDemo xheditorDemo = uploadService.getXheditorDemo(cId);
Blob content = xheditorDemo.getContent();
String blobToString = BlobUtil.BlobToString(content);
return blobToString;
}
5、Blob工具类
/**
* Blob工具类
* @author Administrator
*
*/
public class BlobUtil {
/**
* 将Blob转为String
* @param blob
* @return
* @throws SQLException
* @throws IOException
*/
public static String BlobToString(Blob blob) throws SQLException, IOException {
String reString = "";
InputStream is = blob.getBinaryStream();
ByteArrayInputStream bais = (ByteArrayInputStream) is;
byte[] byte_data = new byte[bais.available()];
bais.read(byte_data, 0, byte_data.length);
reString = new String(byte_data, "utf-8");
is.close();
return reString;
}
/**
* 将String转为Blob
* @param str
* @return
* @throws SerialException
* @throws SQLException
*/
public static Blob StringToBlob(String str) throws SerialException, SQLException {
String value = (str);
byte[] buff = value.getBytes();
Blob blob = new SerialBlob(buff);
return blob;
}
}
6、文件上传工具类
/**
* 本地图片上传工具类
* @param file
* @param filePath
* @param fileName
* @throws Exception
*/
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
/**
* 编码成String
* @param bytes
* @return
*/
public static String getImageEncoder(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
/**
* 解码
* @param imageEncoder
* @return
*/
public static byte[] getImagegetDecoder(String imageEncoder) {
return Base64.getDecoder().decode(imageEncoder);
}
7、html代码(这里可以对ajax进行统一封装,因为是Demo,我就没有封装,在正式项目中进行了相应封装)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Demo</title>
<script type="text/javascript" src="xheditor/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="xheditor/xheditor-1.2.2.min.js"></script>
<script type="text/javascript" src="xheditor/xheditor_lang/zh-cn.js"></script>
</head>
<body>
<div>
<input type="text" placeholder="请输入标题"/>
</div>
<div>
<textarea id="container"></textarea>
</div>
<div>
<button type="button" οnclick="xheditorUploadTest();">提交</button>
<input type="text" id="textId" placeholder="请输入要回显的id"/>
<button type="button" οnclick="xheditorUploadGoBack();">测试数据回显</button>
</div>
<div id="PreviewDIV">
</div>
<script type="text/javascript">
$('#container').xheditor({
width : '100%',
height : '300%',
cleanPaste : 0,
internalScript : true,
inlineScript : true,
linkTag : true,
html5Upload : false,
upMultiple : false,
upImgUrl : "/xheditorImg?id="+getID(),
upImgExt : "jpg,jpeg,gif,bmp,png",
onUpload : insertUpload
});
/* 本地上传回调 */
function insertUpload(msg) {
alert(msg);
}
/* 页面提交 */
function xheditorUploadTest() {
var content = $("#container").val();
var id = getID();
$.ajax({
type:"POST",
url:"mainUpload",
data:{"id":id,"content":content},
dataType:"JSON",
success:function(result){
alert(result)
//$("#PreviewDIV").html(result);
//$("#container").html(result);
}
});
/* $.post("mainUpload",{"id":id,"content":content},function(result){
$("#container").html("");
}); */
}
/*回显数据测试*/
function xheditorUploadGoBack(){
var cId=$("#textId").val();
$.ajax({
type:"POST",
url:"getXhidtor",
data:{'cId':cId},
dataType:"JSON",
success:function(result){
$("#PreviewDIV").html(result);
//$("#container").html(result);
}
});
}
/* 使用当前时间生成唯一标示ID */
function getID() {
var date = new Date();
var month = date.getMonth() + 1;
var strDate = date.getDate();
var currentdate = date.getFullYear() + "" + month + "" + strDate;
return currentdate + new Date().getTime();
}
</script>
</body>
</html>
8、编辑器的目录结构
9、实体类,(省略get set )
@Entity
@Table(name = "xheditor")
public class XheditorDemo implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "c_id")
private String cId;
@Column(name = "content")
private Blob content;
@Column(name = "author")
private String author;
@Column(name = "create_time")
private Date createTime;
@Column(name = "update_time")
private Date updateTime;
10、sql脚本
CREATE TABLE `xheditor` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`c_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_croatian_ci NULL DEFAULT NULL,
`content` blob NULL,
`author` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_croatian_ci NULL DEFAULT NULL,
`create_time` datetime(0) NULL DEFAULT NULL,
`update_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 32 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_croatian_ci ROW_FORMAT = Dynamic;
补充完三层结构,就可以进行测试了。