白雨青工作站发文地址:http://www.byqws.com/blog/1040.html
tinymce 富文本编辑器 java Struts2 从前台到后台数据之间的传递
原创2023-03-21 01:06·白雨青
tinymce 富文本编辑器 java Struts2 从前台到后台数据之间的传递 显示在前台 生成环境具体使用
白雨青工作站发文地址:tinymce 富文本编辑器 java Struts2 从前台到后台数据之间的传递 显示在前台 生成环境具体使用-白雨青工作站
近段时间在研究tinymce 富文本编辑器,网上找不到符合自己实际情况的代码,现在将实现的整个过程把代码记录在此
第一步:下载tinymce 下载方法很多,网上都可以搜到具体的教程,这里强烈推荐官网下载。
第二步:将本网站是如何使用的网站代码贴出来
AddArticle.jsp 新增文章的前台界面代码
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%><%Stringpath = request.getContextPath();StringbasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML><html><head><basehref="<%=basePath%>"><title>写文章-白雨青工作站</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="小说,我有一剑,Java,HTML,Java小工具,白雨青工作站,http://www.byqws.com:8080/byqws">
<metaname="description"content="小说,我有一剑,Java,HTML,Java小工具,白雨青工作站,http://www.byqws.com:8080/byqws/">
<!---->
<linkrel="shortcut icon"href="img/byqws-apple-touch-icon-16X16.png" />
<linkrel="apple-touch-icon"href="img/byqws-apple-touch-icon-57X57.png" />
<linkrel="apple-touch-icon"sizes="72x72"href="img/byqws-apple-touch-icon-72X72.png" />
<linkrel="apple-touch-icon"sizes="114x114"href="img/byqws-apple-touch-icon-144X144.png" />
<linkrel="stylesheet"type="text/css"href="Background/css/addArticle.css">
<metaname="viewport"content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<scripttype="text/javascript"src="js/jquery-1.4.min.js"></script>
<scriptsrc="Background/js/tinymce/tinymce.min.js"type="text/javascript"charset="utf-8"></script>
<scriptsrc="Background/js/tinymce/langs/zh-Hans.js"type="text/javascript"charset="utf-8"></script><!--汉化-->
<scripttype="text/javascript"src="Background/js/AddArticle.js"></script>
<scripttype="text/javascript"src="Background/js/mytinymce.js"></script>
<scripttype="text/javascript"src="Background/js/uploadImg.js"></script>
</head><body><divclass='main'>
<divclass='title'>
<label >添加一篇文章</label>
</div>
<divclass='FTitle_div'>
<inputid="FTitle"class='FTitle'placeholder = '请输入标题'></input>
</div>
<divclass='FAbstract_div'>
<inputid="FAbstract"class='FAbstract'placeholder = '请输入摘要'></input>
</div>
<divclass='content_div'>
<textareaid="content"class='content'></textarea>
</div>
<divclass="FCover">封面图片</div>
<divclass="upload-piclist">
<divclass="upload-file"><inputtype="file"id="file"accept="image/*"multipleonchange="imgChange()"/>
</div></div>
<inputid="submitbutton"class='submitbutton'type = 'button'value = '提交'></input></div></body></html>
引入初始化的tinymce代码
<scripttype="text/javascript"src="Background/js/mytinymce.js"></script>
mytinymce.js
tinymce.init({
selector: '#content',
width:'100%',
height:500,
language:'zh-Hans',
/**/
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'table emoticons template paste help codesample'
],
toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' +
'bullist numlist outdent indent | link image | codesample | print preview media fullpage | ' +
'forecolor backcolor emoticons | help |uploadimage',
menu: {
favs: {title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons'}
},
menubar: 'favs file edit view insert format tools table help',
// object_resizing: false,
paste_data_images: true,
relative_urls : false,
convert_urls: false,
images_upload_handler: function (file, success, failure) {//关键代码var form = new FormData();
// console.log(blobInfo.filename())// console.log(blobInfo.blob())// base64// console.log(file)// console.log(file.filename())// console.log(file.base64())var condition = {};
// addJson(condition,"file.fileFileName",blobInfo.filename());
addJson(condition,"file.base64",file.base64());
// console.log(condition);
$.ajax({
url: 'uploadImage/uploadImage.action' ,
type: "post",
data: condition,
// dataType: 'json',async : false,
// processData: false,// contentType: false,
success: function (data) {
console.log("byq"+data);
var imgUrl =JSON.parse(data).url;//根据返回值得不同这里要自己定义console.log(imgUrl);
success(imgUrl);
},
error: function (e) {
alert("图片上传失败");
}
});
}
});
functionaddJson(json,prop, val) {
// 濡傛灉 val 琚拷鐣?if(typeof val === "undefined") {
// 鍒犻櫎灞炴?// console.log('1=');delete json[prop];
}
else {
// 娣诲姞 鎴?淇敼// console.log('2=');
json[prop] = val;
}
}
Java Struts2 部分:
UploadImageManagementStruts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE strutsPUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"><struts><constantname="struts.enable.DynamicMethodInvocation"value="false" /><constantname="struts.devMode"value="true" /><packagename="uploadImage"namespace="/uploadImage"extends="struts-default">
<actionname="uploadImage"class = "com.byqws.blog.action.UploadImageAction"method="uploadImage" ><result></result></action></package></struts>
UploadImageAction.java
package com.byqws.blog.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.byqws.blog.model.Article;
import com.byqws.blog.model.MyFile;
import com.byqws.blog.service.ArticleService;
import com.byqws.blog.service.impl.ArticleServiceImpl;
import com.byqws.story.model.Chapters;
import com.byqws.story.service.ChaptersService;
import com.byqws.story.service.impl.ChaptersServiceImpl;
import com.byqws.story.tools.Base64ToImg;
import com.byqws.story.tools.ReadApplicationProperties;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
publicclassUploadImageAction{
privateHttpServletResponse response;
privateHttpServletRequest request;
privatestaticString json;
privateString data = null;
privateMyFile file;
// MyFile file = new MyFile();
publicString uploadImage(){
response = ServletActionContext.getResponse();
request = ServletActionContext.getRequest();
System.out.println("v123vvbyq");
try {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
System.out.println("file.getFileFileName()="+file.getFileFileName());
System.out.println("file.getFileContentType()="+file.getFileContentType());
System.out.println("file.getFile()="+file.getFile());
System.out.println("file.file.base64()()="+file.getBase64());
// inf = new Information();// data = request.getParameter(data);// System.out.println(article.getFTitle());// System.out.println(article.getFContent());// System.out.println(article.getFAbstract());// // System.out.println("article.getFCoverBase64()="+article.getFCoverBase64());// System.out.println("article.getFCoverBase64()="+article.getFCoverBase64().length());// String s = article.getFCoverBase64();// System.out.println("s=" + s.replaceAll("\\[\"", ""));// ArticleService articleService = new ArticleServiceImpl();// // article.setFCoverBase64((article.getFCoverBase64().replaceAll("\\[\"", "")).replaceAll("\"\\]", ""));// articleService.save(article);
ReadApplicationProperties r = new ReadApplicationProperties();
Base64ToImg b = new Base64ToImg();
String url = b.ToImg(file.getBase64(), r.read("articleImgPath")).replaceAll(r.read("articleHtmlPath"),r.read("articleXUNIPath"));
// String url = b.ToImg(file.getBase64(), r.read("articleHtmlPath")).replaceAll(r.read("articleHtmlPath"),"/byqws/blog/");
// String url = b.ToImg(file.getBase64(), r.read("articleHtmlPath"));
// String url = "http://localhost/blog/20230312022158173.png";
json = "{\"success\":\"true\",\"msg\":\"'提交成功!'\",\"url\":\""+url+"\"}";
//将流打到客户端
System.out.println("json="+json);
out.print(json);
//清空缓存
out.flush();
//关闭流
out.close();
// System.out.println(iparentId);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
publicString getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
publicMyFile getFile() {
return file;
}
public void setFile(MyFile file) {
this.file = file;
}
}
MyFile.java
package com.byqws.blog.model;
import java.io.File;
publicclassMyFile{
private File file;
private String fileFileName;
private String fileContentType;
private String blobInfo;
private String base64;
public File getFile(){
return file;
}
publicvoidsetFile(File file){
this.file = file;
}
public String getFileFileName(){
return fileFileName;
}
publicvoidsetFileFileName(String fileFileName){
this.fileFileName = fileFileName;
}
public String getFileContentType(){
return fileContentType;
}
publicvoidsetFileContentType(String fileContentType){
this.fileContentType = fileContentType;
}
public String getBlobInfo(){
return blobInfo;
}
publicvoidsetBlobInfo(String blobInfo){
this.blobInfo = blobInfo;
}
public String getBase64(){
return base64;
}
publicvoidsetBase64(String base64){
this.base64 = base64;
}
}
Base64ToImg.java
其中 :ReadApplicationProperties r = new ReadApplicationProperties();
ReadApplicationProperties 类是用来读取配置文件Properties内容的,相关方法网上也有很多,这里不多写,后期会单独写一篇文章专门讲。
到此所有代码都已就位
现在来看效果图