码迷,mamicode.com
首页 > 其他好文 > 详细

xheditor的使用

时间:2014-11-05 21:31:04      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:xheditor

xheditor是一款比较复杂的在线编辑器,默认支持php和asp.net,从官方的demo可以看出,它的复杂度远远大于其他编辑器,站在java的立场思考,这编辑器对java程序员太不公平了。但是没有办法啊,官方没对java做支持咱们可以根据开发文档自己搞啊。

1 先看看这款编辑器长什么样子

bubuko.com,布布扣

看到这里大家就知道了,其实这个就是csdn使用的编辑器


2  显示编辑器的jsp页面


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>xheditor</title>  
   
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page"> 

     <script type="text/javascript" src="xheditor-1.1.7/jquery/jquery-1.4.2.min.js"></script>
	<script type="text/javascript" src="xheditor-1.1.7/xheditor-1.1.7-zh-cn.min.js"></script>
	<script type="text/javascript">
	$(document).ready(function() {
		//初始化xhEditor编辑器插件
		$('#xh_editor').xheditor({
			tools:'full',
			skin:'default',
			upMultiple:true,
			upImgUrl: "servlet/UploadFileServlet",
			upImgExt: "jpg,jpeg,gif,bmp,png",
			upFlashUrl: "servlet/UploadFileServlet",
			upFlashExt: "swf,fla",
			upMediaUrl: "servlet/UploadFileServlet",
			upMediaExt: "flv,avi,wmv,rmvb,mkv",
			onUpload:insertUpload,
			html5Upload:false
		}); 
		//xbhEditor编辑器图片上传回调函数
		function insertUpload(msg) {  
			var _msg = msg.toString();
			
			$("#xh_editor").append(_msg); 
			   
		}
		//chǔ理服务器返回到回调函数的字符串内容,格式是JSON的数据格式.
		function Substring(s){
			return s.substring(s.substring(0,s.lastIndexOf("/")).lastIndexOf("/"),s.length);
		}
		//save
		 $("#save").bind("click",function(){
			    var xh_editor = $("#xh_editor").val().replace(/\s/g, ""); 
			    //alert(xh_editor);
				//alert("last=="+xh_editor);   
				//document.getElementById("froms").submit();
		 });  
	 });
	</script> 
  </head>
  <body> 
  <div class="contents">  
	<form method="POST" name ="froms" id="froms"  action="test/add.html" class="dataForm"> 
		<div class="form"> 
			
			
				<div class="fields-box">
					<em></em><textarea rows="25" cols="160" name="clubDesc" id="xh_editor"  
					style="border: 1px"></textarea>  
				</div>
					<div class="fields-box">
						<input class="button_blue inputS" type="button" id="save" 
							value="确定保存"> 
					</div>
				
			
		</div>
	</form>
</div>
	<div id="uploadList"></div>
  </body>
</html>

复杂的地方在于java程序员要自己写上传文件的代码,而且还要按照xheditor的API规范来弄,其他的倒是没什么,估计如果不熟悉的情况看xheditor的API都要花很多时间


3  文件上传代码的servlet

package com.xheditor.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;

@SuppressWarnings({ "serial", "deprecation" })
public class UploadFileServlet extends HttpServlet {
	
	private static String baseFileDir = File.separator + "uploadFile" + File.separator;//上传文件存储目录
	private static String baseURLDir = "/upload/";//上传文件目录URL
	private static String fileExt = "jpg,jpeg,bmp,gif,png,fla,swf,flv,avi,wmv";
	private static Long maxSize = 0l;

	// 0:不建目录 1:按天存入目录 2:按月存入目录 3:按扩展名存目录 建议使用按天存
	private static String dirType = "1";
	
	/**
	 * 文件上传初始化工作
	 */
	public void init() throws ServletException {
		/*获取文件上传存储的相当路径*/
		if (!StringUtils.isBlank(this.getInitParameter("baseDir"))){
			baseFileDir = this.getInitParameter("baseDir");
		}
		
		String realBaseDir = this.getServletConfig().getServletContext().getRealPath(baseFileDir);
		File baseFile = new File(realBaseDir);
		if (!baseFile.exists()) {
			baseFile.mkdir();
		}

		/*获取文件类型参数*/
		fileExt = this.getInitParameter("fileExt");
		if (StringUtils.isBlank(fileExt)){
			fileExt = "jpg,jpeg,bmp,gif,png,fla,swf,flv,avi,wmv";
		} 

		/*获取文件大小参数*/
		String maxSize_str = this.getInitParameter("maxSize");
		if (StringUtils.isNotBlank(maxSize_str)) maxSize = new Long(maxSize_str); 
		
		/*获取文件目录类型参数*/
		dirType = this.getInitParameter("dirType");
		
		if (StringUtils.isBlank(dirType))
			dirType = "1";
		if (",0,1,2,3,".indexOf("," + dirType + ",") < 0)
			dirType = "1";
	}

	/**
	 * 上传文件数据chǔ理过程
	 */
	@SuppressWarnings({"unchecked" })
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");

		String err = "";
		String newFileName = "";

		DiskFileUpload upload = new DiskFileUpload();
		try {
			List<FileItem> items = upload.parseRequest(request);
			Map<String, Serializable> fields = new HashMap<String, Serializable>();
			Iterator<FileItem> iter = items.iterator();
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField())
					fields.put(item.getFieldName(), item.getString());
				else
					fields.put(item.getFieldName(), item);
			}
			
			/*获取表单的上传文件*/
			FileItem uploadFile = (FileItem)fields.get("filedata");
			
			/*获取文件上传路径名称*/
			String fileNameLong = uploadFile.getName();
			System.out.println("fileNameLong:" + fileNameLong);
			
			/*获取文件扩展名*/
			/*索引加1的效果是只取xxx.jpg的jpg*/
			String extensionName = fileNameLong.substring(fileNameLong.lastIndexOf(".") + 1);
			System.out.println("extensionName:" + extensionName);
			
			/*检查文件类型*/
			if (("," + fileExt.toLowerCase() + ",").indexOf("," + extensionName.toLowerCase() + ",") < 0){
				printInfo(response, "不允许上传此类型的文件", "");
				return;
			}
			/*文件是否为空*/
			if (uploadFile.getSize() == 0){
				printInfo(response, "上传文件不能为空", "");
				return;
			}
			/*检查文件大小*/
			if (maxSize > 0 && uploadFile.getSize() > maxSize){
				printInfo(response, "上传文件的大小超出限制", "");
				return;
			}
			
			//0:不建目录, 1:按天存入目录, 2:按月存入目录, 3:按扩展名存目录.建议使用按天存.
			String fileFolder = "";
			if (dirType.equalsIgnoreCase("1")){
				
				fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
			}
			if (dirType.equalsIgnoreCase("2")){
				
				fileFolder = new SimpleDateFormat("yyyyMM").format(new Date());
			}
			if (dirType.equalsIgnoreCase("3")){
				
				fileFolder = extensionName.toLowerCase();
			}
			
			//工程目录
			String projectPath  = this.getServletContext().getRealPath("/");
			File files = new File(projectPath);
			//上传文件保存目录
			String uploadFilePath = files.getPath()+File.separator + "upload"+File.separator 
					+fileFolder+File.separator;   
			
			
			System.out.println("saveFilePath:" + uploadFilePath);
			
			/*构建文件目录以及目录文件*/
			File fileDir = new File(uploadFilePath);
			if (!fileDir.exists()) {fileDir.mkdirs();}
			
			/*重命名文件*/
			String filename = UUID.randomUUID().toString(); 
			File savefile = new File(uploadFilePath + filename + "." + extensionName);
			
			/*存储上传文件*/
			System.out.println(upload == null);
			uploadFile.write(savefile);
			
		
			String projectBasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort(); 
			newFileName = projectBasePath +"/"+ "xheditordemo"+baseURLDir +fileFolder + "/" + filename + "." + extensionName;		
			System.out.println("newFileName:" + newFileName);
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			newFileName = "";
			err = "错误: " + ex.getMessage();
		}
		printInfo(response, err, newFileName);
	}
	
	/**
	 * 使用I/O流输出 json格式的数据
	 * @param response
	 * @param err
	 * @param newFileName
	 * @throws IOException
	 */
	public void printInfo(HttpServletResponse response, String err, String newFileName) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("{\"err\":\"" + err + "\",\"msg\":\"" + newFileName + "\"}");
		out.flush();
		out.close();
	}
}

这代码看着有点吓人因为太多了,看了头晕,不过没关系,上传文件不一定要用commons-fileupload来弄,像smartupload也可以拿来用


4  使用截图

bubuko.com,布布扣

预览效果如下:

bubuko.com,布布扣


究其功能来看,xheditor要比其他html编辑器少很多,但是应付日常的开发应该够了

至于xheditor的API可以到网上找找,如果需要代码高亮的相关功能可以参考下面的链接

http://www.beijibear.com/index.php?aid=355

http://xheditor.com/manual/2

xheditor的使用

标签:xheditor

原文地址:http://blog.csdn.net/smartcodekm/article/details/40829113

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!