论坛首页 Web前端技术论坛

ckeditor在jsp下增加图片上传功能

浏览 23590 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (10) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-08-28   最后修改:2010-08-28
    ckeditor配合ckfinder是可以实现图片上传功能的,但是只有php和asp支持,找了几天资料,终于成功在jsp上也实现了这个功能。
    参考资料:http://blog.163.com/ytrtfhj@126/blog/static/890531092010226023136/

   先来效果图 







    首先在编辑器完全生成后调用addUploadButton(editor)函数,传入编辑器变量,建议在CKEDITOR.replace之后直接使用.

function addUploadButton(editor){
CKEDITOR.on('dialogDefinition', function( ev ){

               var dialogName = ev.data.name;

               var dialogDefinition = ev.data.definition;

               if ( dialogName == 'image' ){

                   var infoTab = dialogDefinition.getContents( 'info' );

                   infoTab.add({

                       type : 'button',

                       id : 'upload_image',

                       align : 'center',

                       label : '上传',

                       onClick : function( evt ){

                           var thisDialog = this.getDialog();

                           var txtUrlObj = thisDialog.getContentElement('info', 'txtUrl');

                           var txtUrlId = txtUrlObj.getInputElement().$.id;

                           addUploadImage(txtUrlId);

                       }

                   }, 'browse'); //place front of the browser button

               }

           });

       }
function addUploadImage(theURLElementId){

           var uploadUrl = "upload.jsp"; //这是我自己的处理文件/图片上传的页面URL

           var imgUrl = window.showModalDialog(uploadUrl);

          //在upload结束后通过js代码window.returnValue=...可以将图片url返回给imgUrl变量。

           var urlObj = document.getElementById(theURLElementId);
  
           urlObj.value = imgUrl;
   //alert(urlObj.value);
           //urlObj.fireEvent("onchange"); //触发url文本框的onchange事件,以便预览图片
   //urlObj.fireEvent("onchange");
   //urlObj.onchange();
  
   //以下仅支持firefox
   var evt = document.createEvent('HTMLEvents'); 
       evt.initEvent('change',true,true); 
       urlObj.dispatchEvent(   evt   ); 
  
    }

     这里必须提醒的是要注意不同的浏览器事件驱动是不一样的,这个地方卡了我好久,因为我用firefox调试的原因,urlObj.fireEvent("onchange"); 这句代码是不起作用的。
   addUploadImage函数指定文件上传页面的URL,然后在一个模态窗口中打开这个页面,处理文件上传。最终的结果是将图片上传后在服务器上的URL地址返回给一个变量imgUrl。最后把这个变量赋值给传进来的图片URL文本框里。最后手工触发一下onchange事件,这样在image对话框里就能看到图片的预览效果了。


以下为上传jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  
    <form name="form1" method="post" action="imgUpload.do" id="form1" enctype="multipart/form-data">
	    <input type="file" name="imgFile" id="fuPhoto" title="选择图片" />
	    <input type="submit" value="上 传" id="btnUpload" onclick="close"/>
	    <input type="hidden" value="${requestScope.pagePath}" name="pagePath" id="_pagePath" />
    </form>
    <script type="text/javascript">
	    var _pagePath = document.getElementById("_pagePath").value;
	
		//alert(_pagePath);
	    if(null!=_pagePath  && ""!=_pagePath){
	
	       window.returnValue=_pagePath; 
	
	       window.close(); 
	
	    }
  	</script>   
  </body>
</html>


上传的后台处理我用struts1.2写的
UploadForm:
package com.newsManage_10.struts.form;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class UploadForm extends ActionForm {

	private static final long serialVersionUID = 1L;
	private FormFile imgFile;

	public FormFile getImgFile() {
	   return imgFile;
	}

	public void setImgFile(FormFile imgFile) {
	   this.imgFile = imgFile;
	}

	}


ImgUploadAction:
package com.newsManage_10.struts.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import com.newsManage_10.struts.form.UploadForm;



public class ImgUploadAction extends DispatchAction {

	
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("上传图片");
		//获取webroot目录下的upload文件夹的地址,注意要是加入了spring会报空指针异常要更改为
		//ServletContext servletContext = request.getSession().getServletContext();
		//String url = servletContext.getRealPath("/upload") + "\\";
		String url = servlet.getServletContext().getRealPath("/upload") + "\\"; 
		
		int fsize = 5 * 1024 * 1024;
		UploadForm upf = (UploadForm) form;
		FormFile ffi = upf.getImgFile();
		String fileName = ffi.getFileName();

		if (!((fileName.toLowerCase().endsWith(".jpg"))
				|| (fileName.toLowerCase().endsWith(".gif")) || (fileName
				.toLowerCase().endsWith(".png")))) {
			System.out.println("文件类型错误不能上传");
			return null;
		}

		if (ffi.getFileSize() > fsize) {
			System.out.println("文件大于限定大小不能上传");
			return null;
		}
		String fname = null;  //完整地址
		String shortName = null;  //文件名含后缀
		try {
			if ("".equals(fileName)) {
				return null;
			}
			InputStream stream = ffi.getInputStream();

			String extendFile = null;
			if (isJpg(fileName))
				extendFile = ".jpg";
			else if (isGif(fileName))
				extendFile = ".gif";
			else if (isPng(fileName))
				extendFile = ".png";
			else
				extendFile = ".jpg";
			
			shortName = timename() + extendFile;
			fname = url + shortName;//重命名
			File imgFile = new File(fname);
			//如果不存在先创建
			if(!imgFile.exists())
			{
				imgFile.createNewFile();
			}
			//写入服务器
			OutputStream bos = new FileOutputStream(imgFile);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}

			bos.close();
			stream.close();
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		//不能存d:\这种地址,要url
		String path = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/upload/" + shortName;
		request.setAttribute("pagePath", path);
		return mapping.findForward("success");//跳转到成功页面

	}

	//时间命名图片
	public static String timename() {
		String name = null;
		name = Long.toString(new Date().getTime());
		return name;
	}

	//-----文件类型判断------
	public static boolean isGif(String file) {
		if (file.toLowerCase().endsWith(".gif")) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isJpg(String file) {
		if (file.toLowerCase().endsWith(".jpg")) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isPng(String file) {
		if (file.toLowerCase().endsWith(".png")) {
			return true;
		} else {
			return false;
		}
	}

}


struts的配置文件相关部分由于我用了spring所以type内容有所不同
<action
      name="UploadForm"
      path="/imgUpload"
      scope="request"
      type="org.springframework.web.struts.DelegatingActionProxy" 
      parameter="method">
	    <forward name="success" path="/upload.jsp" />
    </action>

<form-bean name="UploadForm" type="com.newsManage_10.struts.form.UploadForm" />
    
   发表时间:2010-09-02  
原来叫FCKeditor,不知道现在为什么叫CK Editor了?
0 请登录后投票
   发表时间:2010-09-03  
InnocentBoy 写道
原来叫FCKeditor,不知道现在为什么叫CK Editor了?



FCKeditor ==  Finder+CKeditor

免费          收费    免费

我还是用fckedtior了,集成需要破解Finder ,因为Finder 现在要钱了!!
0 请登录后投票
   发表时间:2010-09-03  
kjj 写道
InnocentBoy 写道
原来叫FCKeditor,不知道现在为什么叫CK Editor了?



FCKeditor ==  Finder+CKeditor

免费          收费    免费

我还是用fckedtior了,集成需要破解Finder ,因为Finder 现在要钱了!!

真是不明白为什么finder要收费。。。
0 请登录后投票
   发表时间:2010-09-03   最后修改:2010-09-03
楼主做的不错哈,给你个小小的建议,可以根据项目需求,对ckeditor的上传页面进行改造,有些tab是可以删掉的(安全性考虑),这样可以为自己开发的组件库中添加一员猛将,方便以后复用!
0 请登录后投票
   发表时间:2010-09-04  
完了,JE沦陷了,到处充斥着广告!!!
0 请登录后投票
   发表时间:2010-09-05  
还是用fckeditor吧
ckeditor复制word文本时 文本颜色会过滤
考虑到方便性 没有JAVA版本的findeditor远不如fckeditor
0 请登录后投票
   发表时间:2010-09-06   最后修改:2010-09-06
想问一下楼主你是怎么解决图片中文乱码问题的。谢谢。
0 请登录后投票
   发表时间:2010-09-06  
jinnapeng 写道
想问一下楼主你是怎么解决图片中文乱码问题的。谢谢。


verycd 上有个视频,讲FCKEDTOR,讲的非常好,包括中文解决问题。
0 请登录后投票
   发表时间:2010-09-06  
mogui258 写道
jinnapeng 写道
想问一下楼主你是怎么解决图片中文乱码问题的。谢谢。


verycd 上有个视频,讲FCKEDTOR,讲的非常好,包括中文解决问题。


在哪里,链接呢

0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics