ckeditor文本编辑器插件上传功能与struts2的结合

  ckeditor文本编辑器文本编辑器是目前使用比较多,也比较广的一款插件,网上的各种教程也很多,如果不是用他的图片上传功能,真的很简单,我就不需多言了。

因为项目中用到了,没有办法,只好慢慢研究,折腾成功了,那就记下来,方便以后使用,也方便有需求的朋友。

废话不多说,直接来看看怎么用的。首先,我的是3.6.5版本的,最新版的跟这般还是有些许不同的地方。网上下载解压完,将整个文件夹放到WebRoot下。在jsp页面上添加标签,载入js文件,css样式。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
	<script type="text/javascript" src="js/ckeditor/ckeditor.js"></script>
	<script src="sample.js" type="text/javascript"></script>
	<link href="sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<form action="" method="post">
		<p>
			<label for="editor1">
				Editor 1:</label>
			<textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea>
		</p>
		<p>
			<input type="submit" value="Submit" />
		</p>
	</form>
</body>
</html>

这样就算部署配置完了。你在页面中会看到这样的效果。

点击那个图片的图标,会有添加图片的功能

当然,现在你是看不到上传按钮的,这个需要配置。

首先,找到ckeditor/plugins/image/dialogs/image.js,搜索upload,就会看到id:'Upload',hidden:true,默认是隐藏的,只要将true改成false就行。然后,默认在预览中会有很多英文,好吧,我不认识,那就去掉。。。。还是在image.js文件中,搜索那一段话,直接删了。其他的配置。比如隐藏源码按钮,修改样式等等,这个网上有很多,我就不多说了。

接下来,是要说的重点,如何结合struts2来实现上传。

上传功能有两步,第一步,将图片上传到服务器。其实这块就是找到对应的action,实现文件上传就行。

那么,在插件中我们需要配置下,找到config.js文件,在其中加上一段代码:

config.filebrowserUploadUrl="ckeditor_uploadContext";文件对应的上传路径,这里上传文件的name是upload,所以在你的action中要有一个upload属性

	private File upload;  //文件  
	private String uploadContentType;  //文件类型  
	private String uploadFileName;   //文件名 
提供其set,get方法,struts2的上传相信大家都写过,这里我就不多做解释,这也不是这篇博文的重点,因为我的项目中多处用到了上传图片的功能,所以我做了一下封装,而且动态获取了服务器中项目的真实路径,我在最下面贴出代码。

上传到服务器完成后,第二步,回显到预览界面


这里,在action中,上传文件代码后,通过流将图片写出去。

	HttpServletResponse response = ServletActionContext.getResponse();  
        response.setCharacterEncoding("utf-8");  
        PrintWriter out = response.getWriter(); 
	//上传文件
	String newName = fileUpload.uploadFile(upload, uploadFileName);
		
	// 返回“图像”选项卡并显示图片  
        out.println("<script type=\"text/javascript\">");    
        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + "upload/" + newName + "','')");    
        out.println("</script>"); 
到这里就ok了。


下面附上我的图片上传的代码:

1.action

public class CkeditorAction extends ActionSupport {

	private FileUploadUtil fileUpload;
	public void setFileUpload(FileUploadUtil fileUpload) {
		this.fileUpload = fileUpload;
	}
	
	
	private File upload;  //文件  
	private String uploadContentType;  //文件类型  
	private String uploadFileName;   //文件名 
	
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}




	public String uploadContext() throws Exception{
		
		HttpServletResponse response = ServletActionContext.getResponse();  
        response.setCharacterEncoding("utf-8");  
        PrintWriter out = response.getWriter(); 
        
     // CKEditor提交的很重要的一个参数  
        String callback = ServletActionContext.getRequest().getParameter("CKEditorFuncNum");   
          
        String expandedName = "";  //文件扩展名  
        if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {  
            //IE6上传jpg图片的headimageContentType是image/pjpeg,而IE9以及火狐上传的jpg图片是image/jpeg  
            expandedName = ".jpg";  
        }else if(uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")){  
            //IE6上传的png图片的headimageContentType是"image/x-png"  
            expandedName = ".png";  
        }else if(uploadContentType.equals("image/gif")){  
            expandedName = ".gif";  
        }else if(uploadContentType.equals("image/bmp")){  
            expandedName = ".bmp";  
        }else{  
            out.println("<script type=\"text/javascript\">");    
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)');");   
            out.println("</script>");  
            return null;  
        }  
          
        if(upload.length() > 600*1024){  
            out.println("<script type=\"text/javascript\">");    
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件大小不得大于600k');");   
            out.println("</script>");  
            return null;  
        }
		
		//上传文件
		String newName = fileUpload.uploadFile(upload, uploadFileName);
		
		// 返回“图像”选项卡并显示图片  
        out.println("<script type=\"text/javascript\">");    
        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + "upload/" + newName + "','')");    
        out.println("</script>"); 
		
		
		return null;
	}
}
2.文件上传工具类

public class FileUploadUtil {

	@Value("#{file.basePath}")
	private String uploadPath;//通过注解赋值
	
	//获取文件名的后缀名
	public String getExt(String filename){
		System.out.println("---------------1---");
		return FilenameUtils.getExtension(filename);
	}
	
	//同过UUID创建新文件名
	public String newFilename(String filename){
		System.out.println("---------------2---");
		String ext = this.getExt(filename);
		return UUID.randomUUID().toString() + "."+ext;
	}
	
	//实现文件上传,并删除临时文件,返回新的文件名
	public String uploadFile(File file,String filename){
		System.out.println("---------------3---");
		String newName = this.newFilename(filename);
//		uploadPath = getPath();
		System.out.println("上传文件的路径--------------------"+uploadPath);
		
		try{
			
			FileUtils.copyFile(file, new File(uploadPath+"upload",newName));
		}catch(Exception e){
			System.out.println("文件上传失败------------------------");
			throw new RuntimeException(e.getMessage());
		}finally{
		//	file.delete();
			System.out.println(file.getName());
		}
		
		return newName;
	}
	
	public String getPath() {
		
		Properties property = new Properties();
		try {
			property.load(new FileInputStream("/fileUpload.properties"));
		} catch (Exception e) {
			throw new RuntimeException("文件读取异常------------");
		} 
		String basePath = property.getProperty("basePath");
		String filePath = property.getProperty("filePath");
		return basePath+filePath;
	}
	
	
}
3.在监听器中加载路径,tomcat启动时

	/**
	 * 用于获取根路径,赋值到配置文件中
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		System.out.println("------------监听器执行-------------------");
		//1.获取根目录的路径
		String path = event.getServletContext().getRealPath("/");
		System.out.println("根目录路径为------------"+path);
		
		Properties properties = new Properties();
		//定义读取流
		InputStream is = null;
		OutputStream os = null;
		
		try{
			//2.将根目录路径写到配置文件中
			is = this.getClass().getResourceAsStream("/fileUpload.properties");
			os = new FileOutputStream(this.getClass().getResource("/fileUpload.properties").getPath());
			
			//关联流
			properties.load(is);
			//给配置文件赋值
			properties.setProperty("basePath", path);
			//保存配置文件
			properties.store(os, "uploadpath");
			
			
		}catch(Exception e){
			System.out.println("获取上传文件路径异常----------------------------------");
			throw new RuntimeException(e.getMessage());
		}finally{
			//关闭流
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e.getMessage());
				}finally{
					if(os != null){
						try {
							os.close();
						} catch (IOException e) {
							throw new RuntimeException(e.getMessage());
						}
					}
				}
			}
		}
	}


好了,写了这么就,希望对有需要的朋友有帮助。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值