`

xhEditor文件上传的Java实现

 
阅读更多
主要参考了:xhEditor文件上传的Java实现http://easin.iteye.com/blog/692390
另外使用了xhEditor的最新版本:xheditor-1.1.9,上传组件包:smart-upload,json包:
xhEditor官方网站:http://xheditor.com/
下载网址:http://code.google.com/p/xheditor/downloads/list
json官方网址:http://json.org/
下载网址:https://github.com/douglascrockford/JSON-java
引用说法:
1 解压xheditor压缩文件 【demo文件夹中可以查看各种形式的配置实例】,将其中的jquery-1.4.2.min.js、xheditor-zh-cn.min.js【这里暂时使用中文版】以及 xheditor_emot、xheditor_plugins和xheditor_skin三个文件夹拷贝到项目的相应目录
2 在相应html文件的head标签结束之前添加:
<script src="scripts/xheditor/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="scripts/xheditor/xheditor-1.1.9-zh-cn.min.js" type="text/javascript"></script>

xheditor.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>xhEditor example</title>
	<script src="scripts/xheditor/jquery-1.4.2.min.js" type="text/javascript"></script>
	<script src="scripts/xheditor/xheditor-1.1.9-zh-cn.min.js" type="text/javascript"></script>
	
	<script type="text/javascript">
		$(document).ready(function(){
			//初始化xhEditor编辑器插件
			$('#xh_editor').xheditor({
				tools:'full',
				skin:'default',
				upMultiple:false,
				upImgUrl: "/xheditor/servlet/UploadFileServlet2",
				upImgExt: "jpg,jpeg,gif,bmp,png",
				onUpload:insertUpload
			});
			//xbhEditor编辑器图片上传回调函数
			function insertUpload(msg) {
				var _msg = msg.toString();
				var _picture_name = _msg.substring(_msg.lastIndexOf("/")+1);
				var _picture_path = Substring(_msg);
				var _str = "<input type='checkbox' name='_pictures' value='"+_picture_path+"' checked='checked' onclick='return false'/><label>"+_picture_name+"</label><br/>";
				$("#xh_editor").append(_msg);
				$("#uploadList").append(_str);
			}
			//处理服务器返回到回调函数的字符串内容,格式是JSON的数据格式.
			function Substring(s){
				return s.substring(s.substring(0,s.lastIndexOf("/")).lastIndexOf("/"),s.length);
			}
		});
	</script>
  </head>
  
  <body>
  	<form action="" method="post">
  	<div>
  	<textarea id="xh_editor" name="contents" rows="25" style="width:100%; border: 1px"></textarea>
  	</div>
  	<div id="uploadList"></div>
	</form>
  </body>
</html>

UploadFileServlet.java
/**
 * Copyright ? 2009 www.debug.cn
 * All Rights Reserved
 */
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;

/**
 * xhEditor文件上传的Java - Servlet实现.
 * @author easinchu
 *
 */
@SuppressWarnings({ "serial", "deprecation" })
public class UploadFileServlet extends HttpServlet {
	
	private static String baseDir = "/ARTICLE_IMG/";//上传文件存储目录
	private static String fileExt = "jpg,jpeg,bmp,gif,png";
	private static Long maxSize = 0l;

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

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

		/*获取文件大小参数*/
		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";
	}

	/**
	 * 上传文件数据处理过程
	 */
	@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 saveDirPath = baseDir + fileFolder + "/";
			//System.out.println("saveDirPath:" + saveDirPath);
			
			/*文件存储在容器中的绝对路径*/
			String saveFilePath = this.getServletConfig().getServletContext().getRealPath("") + saveDirPath;
			//System.out.println("saveFilePath:" + saveFilePath);
			
			/*构建文件目录以及目录文件*/
			File fileDir = new File(saveFilePath);
			if (!fileDir.exists()) {fileDir.mkdirs();}
			
			/*重命名文件*/
			String filename = UUID.randomUUID().toString();
			File savefile = new File(saveFilePath + filename + "." + extensionName);
			
			/*存储上传文件*/
			//System.out.println(upload == null);
			uploadFile.write(savefile);
			
			//这个地方根据项目的不一样,需要做一些特别的定制。
			newFileName = "/xheditor" + saveDirPath + 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();
		//String filename = newFileName.substring(newFileName.lastIndexOf("/") + 1);
		out.println("{\"err\":\"" + err + "\",\"msg\":\"" + newFileName + "\"}");
		out.flush();
		out.close();
	}
}


jspsmart组件上传:

package com.xheditor.servlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
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.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.jspsmart.upload.SmartUploadException;

@SuppressWarnings( { "serial", "deprecation" })
public class UploadFileServlet2 extends HttpServlet {

	private static String baseDir = "ARTICLE_IMG/";// 上传文件存储目录
	private static String fileExt = "jpg,jpeg,bmp,gif,png";
	private static Long maxSize = 0L;
	// 0:不建目录 1:按天存入目录 2:按月存入目录 3:按扩展名存目录 建议使用按天存
	private static String dirType = "1";

	/**
	 * 文件上传初始化工作
	 */
	public void init() throws ServletException {
		/* 获取web.xml中servlet的配置文件目录参数 */
		baseDir = this.getInitParameter("baseDir");

		/* 获取文件上传存储的相当路径 */
		if (StringUtils.isBlank(baseDir))
			baseDir = "ARTICLE_IMG/";

		String realBaseDir = this.getServletConfig().getServletContext()
				.getRealPath(baseDir);
		File baseFile = new File(realBaseDir);
		if (!baseFile.exists()) {
			baseFile.mkdir();
		}

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

		/* 获取文件大小参数 */
		String maxSize_str = this.getInitParameter("maxSize");
		if (StringUtils.isNotBlank(maxSize_str))
			maxSize = new Long(maxSize_str);
		else {
			maxSize = 1024 * 1024L;
		}

		/* 获取文件目录类型参数 */
		dirType = this.getInitParameter("dirType");

		if (StringUtils.isBlank(dirType))
			dirType = "1";
		if (",0,1,2,3,".indexOf("," + dirType + ",") < 0)
			dirType = "1";
	}

	/**
	 * 上传文件数据处理过程
	 */
	@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");
		
		if ("application/octet-stream".equals(request.getContentType())) { // HTML5 上传
			
			try {

				String dispoString = request.getHeader("Content-Disposition");
				int iFindStart = dispoString.indexOf("name=\"") + 6;
				int iFindEnd = dispoString.indexOf("\"", iFindStart);
				iFindStart = dispoString.indexOf("filename=\"") + 10;
				iFindEnd = dispoString.indexOf("\"", iFindStart);
				String sFileName = dispoString.substring(iFindStart, iFindEnd);
				int i = request.getContentLength();
				byte buffer[] = new byte[i];
				int j = 0;
				while (j < i) { // 获取表单的上传文件
					int k = request.getInputStream().read(buffer, j, i - j);
					j += k;
				}

				if (buffer.length == 0) { // 文件是否为空
					printInfo(response, "上传文件不能为空", "");
					return;
				}

				if (maxSize > 0 && buffer.length > maxSize) { // 检查文件大小
					printInfo(response, "上传文件的大小超出限制", "");
					return;
				}

				String filepathString = getSaveFilePath(sFileName, response);

				if ("不允许上传此类型的文件".equals(filepathString))
					return; // 检查文件类型

				BufferedOutputStream out = new BufferedOutputStream(
						new FileOutputStream(this.getServletConfig()
								.getServletContext().getRealPath("")
								+ filepathString, true));

				out.write(buffer);
				out.close();
				String newFileName = request.getContextPath() + filepathString;
				printInfo(response, "", newFileName);
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		} else {
			
			// 执行文件上传
			try {

				com.jspsmart.upload.SmartUpload smartUpload = new com.jspsmart.upload.SmartUpload();
				smartUpload.initialize(getServletConfig(), request, response);
				smartUpload.upload();
				// 设置上传的文件的最大小
				smartUpload.setMaxFileSize(maxSize);
				// 设定可以上传的文件的后缀名
				smartUpload.setAllowedFilesList(fileExt);
				// 设定不能上传的文件的后缀名
				// smartUpload.setDeniedFilesList("");
				// com.jspsmart.upload.Request rqest = smartUpload.getRequest();

				// 检查文件夹是否存在
				/** 图片文件夹名称:以当前日期 */
				SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
				String curretnDate = formatter.format(new Date());

				// 图片相对路径
				String imgPath = baseDir + curretnDate;

				String webAppPath = this.getServletContext().getRealPath("/")
						+ "/" + imgPath;
				File webFile = new File(webAppPath);
				if (!webFile.isFile()) {
					webFile.mkdir();
				}				

				// 图片名称
				String imgName = null;
				String fileExt = null;

				int fileCounts = smartUpload.getFiles().getCount();
				for (int i = 0; i < fileCounts; i++) {
					com.jspsmart.upload.File myFile = smartUpload.getFiles()
							.getFile(i);
					if (!myFile.isMissing()) {

						fileExt = myFile.getFileExt();
						// 文件后缀
						imgName = System.currentTimeMillis() + "." + fileExt;
						imgPath += "/" + imgName;
						// 生成图片文件
						myFile.saveAs(webAppPath + "/" + imgName);					

					}
				}
				
				printInfo(response, "", imgPath);

			} catch (SmartUploadException e) {
				e.printStackTrace();
			}
		}

	}

	public String getSaveFilePath(String sFileName, HttpServletResponse response)
			throws IOException {

		String extensionName = sFileName
				.substring(sFileName.lastIndexOf(".") + 1); // 获取文件扩展名
		if (("," + fileExt.toLowerCase() + ",").indexOf(","
				+ extensionName.toLowerCase() + ",") < 0) { // 检查文件类型
			printInfo(response, "不允许上传此类型的文件", "");
			return "不允许上传此类型的文件";

		}

		String fileFolder = ""; 
		// 0:不建目录, 1:按天存入目录, 2:按月存入目录,3:按扩展名存目录.建议使用按天存

		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 saveDirPath = baseDir + fileFolder + "/"; // 文件存储的相对路径
		String saveFilePath = this.getServletConfig().getServletContext()
				.getRealPath("")+"/"+ saveDirPath; // 文件存储在容器中的绝对路径

		File fileDir = new File(saveFilePath); // 构建文件目录以及目录文件
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}
		String filename = UUID.randomUUID().toString(); // 重命名文件
		return saveDirPath + filename + "." + extensionName;
	}

	/**
	 * 使用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();
		try {
			JSONObject json = new JSONObject().put("err", err).put("msg",
					newFileName);
			out.print(json);
		} catch (JSONException e) {
			out.print("{\"err\":\"对不起,文件上传失败!!请重试..\"}");
			e.printStackTrace();
		}
		out.flush();
		out.close();
	}
}
分享到:
评论

相关推荐

    xhEditor文件上传的Java实现.pdf

    xhEditor文件上传的Java实现.pdf

    xhEditor编缉器下使用java上传的类文件

    xhEditor编缉器,用于java开发时,上传文件,同时解决了在火狐上使用时报错的问题,主要是因为火狐上传时使用的是HTML5,如何解决请花1分吧!! 记得把xheditor里的上传改成servlet的路径呀!!

    xheditor for java

    java 下使用xheditor,可实现数据存储于数据库中,并实现即见即所得显示在页面,便于批量排版

    xheditor编辑器实现图片上传

    基于轻量级的JQuery的xheditor编辑器+jsp实现图上传功能

    jquery.xheditor和jquery,uploadify实现文件上传完整实例

    jquery xheditor是jquery中较好的编辑器插件,而jquery.uploadify也是jquery实现文件上传很优秀的插件,本项目实例解决了两个插件文件上传的问题,对于应用学习两个插件,实现文件上传,具有很好的参考价值,同时本例子是...

    用于xheditor编辑器上传功能的配置文件

    用于xheditor编辑器上传功能的配置文件 upload.aspx,直接下载拷贝到项目根目录下即可。 里面的该行: string attachdir ="../upload"; 是上传路径,根据实际引用xheditor的页面位置,要进行相应的修改,要不然无法...

    xhEditor struts2实现图片上传

    参考博文:http://blog.csdn.net/itmyhome1990/article/details/38491205

    xheditor Java代码

    xheditor Java代码 火狐 ie 支持

    xheditor-1.1.14

    如果想实现更加复杂的交互应用,或者希望xhEditor编辑器能够和自己的Javascript代码实现互相访问,那么你可以选择使用方法2,相对具有更大的自由空间。 xhEditor也提供了即时的卸载编辑器方法: $('#elm1')....

    xheditor 在线编辑器jsp/ava实现版

    xheditor是非常实用的web应用在线编辑器,本程序通过jsp/java实现,可上传图片、视频、远程抓图上传(如QQ截图后直接粘贴在编辑器后自动上传到服务器保存),非常方便、实用。

    XhEditor ubb c#实现

    XhEditor ubb c#实现.。

    Xheditor 富文本编辑器 Java版

    java版 xheditor富文本编辑器,个人认为比fckeditor好用且美观。实现了图片上传功能。示例为myeclipse工程,导入即可用。

    xheditor 1.2.2.zip

    内置强大的Ajax上传,包括HTML4和HTML5上传支持(多文件上传、真实上传进度及文件拖放上传),追求完美的用户上传体验。 Word完美支持 实现Word代码自动检测并清理,提供高效完美的Word代码过滤方案,生成代码最优化...

    ASP.NET应用Xheditor上传图片 jquery-1.11.0

    xheditor-1.2.1 上传图片 jquery版本:jquery-1.11.0 ASP.NET环境

    akcms后台xheditor编辑器高亮代码

    1.上传附件根目录下的face和prettify文件夹上传到你的网站根目录 2.把附件里面的akcms后台/include/xh下面的文件都复制到你网站对应的xh目录下. 最后,因为使用了高亮代码功能.那么在您的内容模板里面需要插入2段...

    xheditor-1.1.11

    xhEditor可以在您的CMS、博客、论坛、商城等互联网平台上完美的嵌入运行,能够非常灵活简单的和您的系统实现完美的无缝衔接。 自2009年4月首个版本发布以来,凭借我们人性化的用户体验和不断持续完善的态度,越来越...

    在xheditor在线编辑器下,ASP提交远程图片自动上传到服务器

    在xheditor在线编辑器下,ASP提交远程图片自动上传到服务器

    xheditor1.1.13在ASPNET开发网站中的使用

    xheditor1.1.13在ASPNET开发网站中的使用,C#,vs2013,实现在线编辑html流,包括本地图片的上传,非常简洁,稍加扩充可用于自己的网站(如博客网站等) 本例xheditor控件采用自定义模式,可参照进行重新配置,实现控件的增减,...

    xhEditor实现插入代码功能

    博文参考地址:http://blog.csdn.net/itmyhome1990/article/details/38495623

Global site tag (gtag.js) - Google Analytics