Struts2版的kindEditor

本文详细介绍了如何使用kindEditor在Struts2框架中处理上传图片,包括图片压缩、目录转移和错误处理。通过创建专门的action,实现图片的上传、保存和返回JSON响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


kindEditor是个免费的html编辑器,而且界面也做的很好看,可以在不调整样式的情况下在项目中直接使用。

kindeditor左边的是链接


对比。。。。。。

接下来在将kindeditor中的两个处理文件的东西

大家在解压后的jsp目录就可以看到。

我下面贴转成action后,里面的代码。

注意:

1、不要轻易在有kindeditor的页面引入或有样式是直接影响表格或div的样式

如:

<style type="text/css">

table *{}

div{

}

</style>

这样容易使kindeditor变形

2、如果提示文件有乱码,在引入kindeditor.js的<script type="text/javascript"  ></script>

charset="gb2312"

原因可能是原js文件本身是gb2312,而这边的项目对不上号


3、注意要引入两个包


common-fileupload和common-io


struts2这些是有的,这种就不多说了。

4、在页面中的使用

接下来是帖action里的代码


由于只是检测文件,没有执行什么修改或要提示的对应页面,是直接返回打印的结果。所以没有result

对应的图片在上传时的名字,毕竟是Struts2得有名字才方便找东东


来上主菜了,

action

其实也就是把它内部原本处理上传的jsp页面中的代码抠到action中来用

package com.news.action;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.simple.JSONObject;
import java.util.*;
import java.io.*;
import java.text.SimpleDateFormat;
import org.json.simple.*;

/**
 * 因为action对表单的特殊处理,不相对别的操作照成潜在影响,
 * 新建来为kindEditor的上传图片做处理的action
 * 
 * 这次实现图片的压缩和目录的转移,将 logo ,dessenamte ,广告 , 编辑器上传的图片的目录指定为 /image/up/ ,/image/up/ad/ 和 /image/up/ed/
 * 商家,团购项目在(AssociateServlet也是
 * 为接下来的数据打包做准备
 *
 * @author 蔡海斌
 * 
 * @version 2011 10 16  
 */
public class EDAction extends BaseAction{
	private File imgFile;
	private String imgFileFileName;
	private String imgFileContentType;
	public File getImgFile() {
		return imgFile;
	}
	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}
	public String getImgFileFileName() {
		return imgFileFileName;
	}
	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}
	public String getImgFileContentType() {
		return imgFileContentType;
	}
	public void setImgFileContentType(String imgFileContentType) {
		this.imgFileContentType = imgFileContentType;
	}
	public String upload_json()throws Exception{
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		setRoot();
		try {
			String savePath=rootPath_+ "image/ed/";
			//文件保存目录URL
			String saveUrl  =basePath+"image/ed/";
			//定义允许上传的文件扩展名
			String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
			//最大文件大小
			long maxSize = 1000000;
			response.setContentType("text/html; charset=UTF-8");

			if(!ServletFileUpload.isMultipartContent(request)){
				out.println(getError("请选择文件。"));
				throw new Exception("未选择上传文件!");
			}
			//检查目录
			File uploadDir = new File(savePath);
			if(!uploadDir.isDirectory()){
				out.println(getError("上传目录不存在。"));
				throw new Exception("上传目录不存在。");
			}
			//检查目录写权限
			if(!uploadDir.canWrite()){
				out.println(getError("上传目录没有写权限。"));
				throw new Exception("上传目录没有写权限。");
			}
			
			//创建文件夹
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			savePath += ymd + "/";
			saveUrl += ymd + "/";
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

		//	FileItemFactory factory = new DiskFileItemFactory();
			//ServletFileUpload upload = new ServletFileUpload(factory);
			
			//upload.setHeaderEncoding("UTF-8");
			
		//	List items = upload.parseRequest(request);
			
			
			//Iterator itr = items.iterator();
			
			//while (itr.hasNext()) {
			//	FileItem item = (FileItem) itr.next();
				String fileName = imgFileFileName;// item.getName();
				long fileSize = imgFile.length();//getSize();
				//if (!item.isFormField()) {
					//检查文件大小
					if(fileSize> 1024*1024){
						out.println(getError("上传文件大小超过限制。"));
						throw new Exception("上传文件大小超过限制。");
					}
					//检查扩展名
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					if(!Arrays.<String>asList(fileTypes).contains(fileExt)){
						out.println(getError("上传文件扩展名是不允许的扩展名。"));
						throw new Exception("上传文件扩展名是不允许的扩展名。");
					}

					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
					String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
					try{
						File uploadedFile = new File(savePath, newFileName);
						imgFile.renameTo(uploadedFile);
					}catch(Exception e){
						out.println(getError("上传文件失败。"));
						throw new Exception("上传文件失败。");
					}

					JSONObject obj = new JSONObject();
					obj.put("error", 0);
					obj.put("url", saveUrl + newFileName);
					out.println(obj.toJSONString());
				//}
		//	}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		out.flush();
		out.close();
		return null;
	}
	private static String rootPath_=null;
	public void setRoot(){
		if(rootPath_==null){
			rootPath_=request.getSession().getServletContext().getRealPath("/");
		}
	}
	public String file_manager_json()throws Exception{
		PrintWriter out=response.getWriter();
		JSONObject result;
		try {
			/**
			 * KindEditor JSP
			 *
			 * 本JSP程序是演示程序,建议不要直接在实际项目中使用。
			 * 如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
			 *
			 */
			setRoot();
			String path2 = request.getContextPath();
			
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path2+"/";
			
			//根目录路径,可以指定绝对路径,比如 /var/www/attached/
			String rootPath = rootPath_+ "image/up/ed/";
			//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
			String rootUrl  = basePath;
			//图片扩展名
			String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

			//根据path参数,设置各路径和URL
			String path = request.getParameter("path") != null ? request.getParameter("path") : "";
			String currentPath = rootPath + path;
			String currentUrl = rootUrl + path;
			String currentDirPath = path;
			String moveupDirPath = "";
			if (!"".equals(path)) {
				String str = currentDirPath.substring(0, currentDirPath.length() - 1);
				moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
			}

			//排序形式,name or size or type
			String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

			//不允许使用..移动到上一级目录
			if (path.indexOf("..") >= 0) {
				out.println("Access is not allowed.");
				throw new Exception("Access is not allowed.");
			}
			//最后一个字符不是/
			if (!"".equals(path) && !path.endsWith("/")) {
				out.println("Parameter is not valid.");
				throw new Exception("Parameter is not valid.");
			}
			//目录不存在或不是目录
			File currentPathFile = new File(currentPath);
			if(!currentPathFile.isDirectory()){
				out.println("Directory does not exist.");
				throw new Exception("Directory does not exist.");
			}

			//遍历目录取的文件信息
			List<Hashtable> fileList = new ArrayList<Hashtable>();
			if(currentPathFile.listFiles() != null) {
				for (File file : currentPathFile.listFiles()) {
					Hashtable<String, Object> hash = new Hashtable<String, Object>();
					String fileName = file.getName();
					if(file.isDirectory()) {
						hash.put("is_dir", true);
						hash.put("has_file", (file.listFiles() != null));
						hash.put("filesize", 0L);
						hash.put("is_photo", false);
						hash.put("filetype", "");
					} else if(file.isFile()){
						String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
						hash.put("is_dir", false);
						hash.put("has_file", false);
						hash.put("filesize", file.length());
						hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
						hash.put("filetype", fileExt);
					}
					hash.put("filename", fileName);
					hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
					fileList.add(hash);
				}
			}

			if ("size".equals(order)) {
				Collections.sort(fileList, new SizeComparator());
			} else if ("type".equals(order)) {
				Collections.sort(fileList, new TypeComparator());
			} else {
				Collections.sort(fileList, new NameComparator());
			}
			result = new JSONObject();
			result.put("moveup_dir_path", moveupDirPath);
			result.put("current_dir_path", currentDirPath);
			result.put("current_url", currentUrl);
			result.put("total_count", fileList.size());
			result.put("file_list", fileList);
			out.println(result.toJSONString());
			response.setContentType("application/json; charset=UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.flush();
		out.close();
		return null;
	}
	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
}

class NameComparator implements Comparator {
	public int compare(Object a, Object b) {
		Hashtable hashA = (Hashtable)a;
		Hashtable hashB = (Hashtable)b;
		if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
			return -1;
		} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
			return 1;
		} else {
			return ((String)hashA.get("filename")).compareTo((String)hashB.get("filename"));
		}
	}
}
class SizeComparator implements Comparator {
	public int compare(Object a, Object b) {
		Hashtable hashA = (Hashtable)a;
		Hashtable hashB = (Hashtable)b;
		if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
			return -1;
		} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
			return 1;
		} else {
			if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) {
				return 1;
			} else if (((Long)hashA.get("filesize")) < ((Long)hashB.get("filesize"))) {
				return -1;
			} else {
				return 0;
			}
		}
	}
}
class TypeComparator implements Comparator {
	public int compare(Object a, Object b) {
		Hashtable hashA = (Hashtable)a;
		Hashtable hashB = (Hashtable)b;
		if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
			return -1;
		} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
			return 1;
		} else {
			return ((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype"));
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值