富文本编辑器ueditor的简单实现,及编辑器加载的图片不自适应的问题

来源:互联网 发布:软件服务保密合同范本 编辑:程序博客网 时间:2024/04/29 04:15

1.在很多地方会用到富文本百度富文本编辑器

2.先下载文件包,引入到项目中如图:


3.在jsp里面引入js

    <script type="text/javascript" charset="utf-8" src="<%=request.getContextPath() %>/ueditor/ueditor.config.js"></script>    <script type="text/javascript" charset="utf-8" src="<%=request.getContextPath() %>/ueditor/ueditor.all.js"> </script>    <!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->    <script type="text/javascript" charset="utf-8" src="<%=request.getContextPath() %>/ueditor/lang/zh-cn/zh-cn.js"></script>
4.在页面写上编辑器

<textarea name="editor" id="editor" style="width: 600px;height: 150px"></textarea>

5.不上传图片就ok了如果要上传图片还的加个上传图片的类,jsp引入

目录:ueditor/jsp/imageUp.jsp



5.Uploader类写法:

package wxnotice.ueditor;import java.io.*;import java.text.SimpleDateFormat;import java.util.*;import org.apache.commons.io.IOUtils;import org.apache.commons.fileupload.*;import org.apache.commons.fileupload.servlet.*;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.log4j.Logger;import sun.misc.BASE64Decoder;//import wxnotice.cn.com.zhongway.base.weixin.action.UpLoadAction;import javax.servlet.http.HttpServletRequest;/** * UEditor文件上传辅助类 *  */public class Uploader {//private static final Logger LOGGER = Logger.getLogger(UpLoadAction.class);// 文件大小常量, 单位kb//private static final int MAX_SIZE = 500 * 1024;// 输出文件地址private String url = "";// 上传文件名private String fileName = "";// 状态private String state = "";// 文件类型private String type = "";// 原始文件名private String originalName = "";// 文件大小private String size = "";private HttpServletRequest request = null;private String title = "";// 保存路径本项目的upload里面private String savePath = "upload";// 文件允许格式private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };// 文件大小限制,单位Byteprivate long maxSize = 0;private HashMap<String, String> errorInfo = new HashMap<String, String>();private Map<String, String> params = null;// 上传的文件数据private InputStream inputStream = null;public static final String ENCODEING = System.getProperties().getProperty("file.encoding");public Uploader(HttpServletRequest request) {this.request = request;this.params = new HashMap<String, String>();this.setMaxSize(50*1024);//设置上传文件的大小,最大10MHashMap<String, String> tmp = this.errorInfo;tmp.put("SUCCESS", "SUCCESS"); // 默认成功// 未包含文件上传域tmp.put("NOFILE","\\u672a\\u5305\\u542b\\u6587\\u4ef6\\u4e0a\\u4f20\\u57df");// 不允许的文件格式tmp.put("TYPE","\\u4e0d\\u5141\\u8bb8\\u7684\\u6587\\u4ef6\\u683c\\u5f0f");// 文件大小超出限制tmp.put("SIZE","\\u6587\\u4ef6\\u5927\\u5c0f\\u8d85\\u51fa\\u9650\\u5236");// 请求类型错误tmp.put("ENTYPE", "\\u8bf7\\u6c42\\u7c7b\\u578b\\u9519\\u8bef");// 上传请求异常tmp.put("REQUEST", "\\u4e0a\\u4f20\\u8bf7\\u6c42\\u5f02\\u5e38");// 未找到上传文件tmp.put("FILE", "\\u672a\\u627e\\u5230\\u4e0a\\u4f20\\u6587\\u4ef6");// IO异常tmp.put("IO", "IO\\u5f02\\u5e38");// 目录创建失败tmp.put("DIR", "\\u76ee\\u5f55\\u521b\\u5efa\\u5931\\u8d25");// 未知错误tmp.put("UNKNOWN", "\\u672a\\u77e5\\u9519\\u8bef");this.parseParams();}public void upload() throws Exception {boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);if (!isMultipart) {this.state = this.errorInfo.get("NOFILE");return;}if (this.inputStream == null) {//this.state = this.errorInfo.get("FILE");this.state = this.errorInfo.get("SIZE");return;}// 存储titlethis.title = this.getParameter("pictitle");try {System.out.println("savePath:"+savePath);String savePath = this.getFolder(this.savePath);System.out.println("savePath:"+savePath);if (!this.checkFileType(this.originalName)) {this.state = this.errorInfo.get("TYPE");return;}this.fileName = this.getName(this.originalName);this.type = this.getFileExt(this.fileName);this.url = savePath + "/" + this.fileName; System.out.println("FILENAME:"+this.fileName);//this.url=this.fileName;FileOutputStream fos = new FileOutputStream(this.getPhysicalPath(this.url));//System.out.println("URL:"+this.url);BufferedInputStream bis = new BufferedInputStream(this.inputStream);int ff = this.inputStream.available();int dd = bis.available();byte[] buff = new byte[128];int count = -1;while ((count = bis.read(buff)) != -1) {fos.write(buff, 0, count);}bis.close();fos.close();//LOGGER.info("ImgUTIL:"+this.getPhysicalPath(this.url)+",name:"+this.fileName.replace(".", ",").split(",")[0]);//ImgUtil.savePic(this.getPhysicalPath(this.url), this.fileName.replace(".", ",").split(",")[0]);this.state = this.errorInfo.get("SUCCESS");} catch (Exception e) {e.printStackTrace();this.state = this.errorInfo.get("IO");}}/** * 接受并保存以base64格式上传的文件 *  * @param fieldName */public void uploadBase64(String fieldName) {String savePath = this.getFolder(this.savePath);String base64Data = this.request.getParameter(fieldName);this.fileName = this.getName("test.png");this.url = savePath + "/" + this.fileName;BASE64Decoder decoder = new BASE64Decoder();try {File outFile = new File(this.getPhysicalPath(this.url));OutputStream ro = new FileOutputStream(outFile);byte[] b = decoder.decodeBuffer(base64Data);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {b[i] += 256;}}ro.write(b);ro.flush();ro.close();this.state = this.errorInfo.get("SUCCESS");} catch (Exception e) {this.state = this.errorInfo.get("IO");}}public String getParameter(String name) {return this.params.get(name);}/** * 文件类型判断 *  * @param fileName * @return */private boolean checkFileType(String fileName) {Iterator<String> type = Arrays.asList(this.allowFiles).iterator();while (type.hasNext()) {String ext = type.next();if (fileName.toLowerCase().endsWith(ext)) {return true;}}return false;}/** * 获取文件扩展名 *  * @return string */private String getFileExt(String fileName) {return fileName.substring(fileName.lastIndexOf("."));}private void parseParams() {DiskFileItemFactory dff = new DiskFileItemFactory();try {ServletFileUpload sfu = new ServletFileUpload(dff);sfu.setSizeMax(this.maxSize);sfu.setHeaderEncoding(Uploader.ENCODEING);FileItemIterator fii = sfu.getItemIterator(this.request);while (fii.hasNext()) {FileItemStream item = fii.next();// 普通参数存储if (item.isFormField()) {this.params.put(item.getFieldName(),this.getParameterValue(item.openStream()));} else {// 只保留一个if (this.inputStream == null) {this.inputStream = item.openStream();this.originalName = item.getName();return;}}}} catch (Exception e) {this.state = this.errorInfo.get("UNKNOWN");}}/** * 依据原始文件名生成新文件名 *  * @return */private String getName(String fileName) {Random random = new Random();return this.fileName = "" + random.nextInt(10000)+ System.currentTimeMillis() + this.getFileExt(fileName);}/** * 根据字符串创建本地目录 并按照日期建立子目录返回 *  * @param path * @return */private String getFolder(String path) {SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");//path += "/" + formater.format(new Date());File dir = new File(this.getPhysicalPath(path));if (!dir.exists()) {try {dir.mkdirs();} catch (Exception e) {this.state = this.errorInfo.get("DIR");return "";}}return path;}/** * 根据传入的虚拟路径获取物理路径 *  * @param path * @return */private String getPhysicalPath(String path) {//String servletPath = this.request.getServletPath();//当前应用的路径。String realPath = this.request.getSession().getServletContext().getRealPath("/upload/pic");//当前应用路径的父路径,如果没有父路径返回null.return new File(realPath).getParent() + "/" + path;}/** * 从输入流中获取字符串数据 *  * @param in *            给定的输入流, 结果字符串将从该流中读取 * @return 从流中读取到的字符串 */private String getParameterValue(InputStream in) {BufferedReader reader = new BufferedReader(new InputStreamReader(in));String result = "";String tmpString = null;try {while ((tmpString = reader.readLine()) != null) {result += tmpString;}} catch (Exception e) {// do nothing}return result;}private byte[] getFileOutputStream(InputStream in) {try {return IOUtils.toByteArray(in);} catch (IOException e) {return null;}}public void setSavePath(String savePath) {this.savePath = savePath;}public void setAllowFiles(String[] allowFiles) {this.allowFiles = allowFiles;}public void setMaxSize(long size) {this.maxSize = size * 1024;}public String getSize() {return this.size;}public String getUrl() {return this.url;}public String getFileName() {return this.fileName;}public String getState() {return this.state;}public String getTitle() {return this.title;}public String getType() {return this.type;}public String getOriginalName() {return this.originalName;}}
说明Uploader类里面有你图片保存的路径设置本次设置的路径是upload/pic下面。你可以先在你的项目下面建一个空的文件放上传的照片
上面两步如图:


ueditor/ueditor.config.js
6.一些小的改动如果页面上的按钮太多想自己设置都在ueditor/ueditor.config.js里面设置。比如编辑器的图标和实际效果图对比




7.说个小问题,编辑器上传的图片能自己设置高度和宽度,但是如果在不同手机上看,我这是给微信群发的消息做的编辑文本的,最后图片不能自适应,在各个手机上显示宽度有的被遮了有的太小,不能自适应,要解决这个问题要改js源码。改如下:

目录:ueditor\ueditor.all.js

改动的地方:

 str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +                    //记载图片自适应的代码开始                    ' style="width:100%; height:auto;"  '+                    //记载图片自适应的代码结束                    (ci.width ? 'width="' + ci.width + '" ' : '') +
说明就是上文 ' style="width:100%; height:auto;" ' +
的代码是我自己加的,大约在10393行,你搜索  <img 这个标签就能找到。

最后结果:


完结!




原创粉丝点击