CKEditor使用含上传图片

9 篇文章 0 订阅
JSP:
<script type="text/javascript" src="<%=path%>/js/ckeditor/ckeditor.js"></script>
...
<script type="text/javascript">
var editor = CKEDITOR.replace("tiJiao");
</script>
JS:
var tiJiao = CKEDITOR.instances.tiJiao.getData(); // 获得编辑器内容
CONFIG.JS:
config.filebrowserImageUploadUrl  = getPath() + '/qtspjgServlet.json?imageUpload=true';  // 上传图片到服务器	
config.removeDialogTabs = 'image:advanced;link:advanced';// 去除 p body 啥的
config.image_previewText = ' '; //清空预览区域显示内容
image.js: 
id:"Upload",hidden:0  // 显示上传tab页面


上传图片:

@RequestMapping (params = "imageUpload")
    public void imageUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException, IOException {
    	String excleFileUrl = "";
    	Map map2 = ParamsUtil.requestNewParamMap(ParamsUtil.requestParamMap(request));
    	out = response.getWriter();
    	UserInfo userBean = (UserInfo)request.getSession().getAttribute("blspLicense");
    	if (userBean == null) {
    		out.print("session过期,请重新登录!");
    		return;
    	}
    	List<FileItem> fileList = null;
    	String basePath = "";
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    	if (isMultipart) {
    		DiskFileItemFactory factory = new DiskFileItemFactory();
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		upload.setHeaderEncoding("UTF-8");
    		try {
    			fileList = upload.parseRequest(request);
    			excleFileUrl = getExcleFileUrl (map2,fileList);
    			excleFileUrl=java.net.URLDecoder.decode(excleFileUrl, "utf-8"); 
    			String fileName=FilenameUtils.getName(excleFileUrl);  
    			basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+request.getContextPath()+"/"+ "upload" + "/" +fileName;// 不要用本地环境地址,就算在本地,也要获得本地服务器环境地址+具体的文件目录。
    		} catch ( FileUploadException e ) {
    			e.printStackTrace();
    		}
    		finally {
    	        response.setContentType("text/html;charset=UTF-8");
    	        String callback = request.getParameter("CKEditorFuncNum");
    	        out.println("<script type=\"text/javascript\">");
    	        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + basePath + "','')");
    	        out.println("</script>");
    	        out.flush();
    	        out.close();
    		}
    	}
    }

 
/**
     * 将上传的文件 放到指定文件夹中
     */
    public String getExcleFileUrl (Map<String, Object> map,List<FileItem> fileList){
        JSONObject object = new JSONObject();
        FileOutputStream fos = null;
        InputStream is = null;
        String msg = null;
        String fileUploadPath = "";
        try {
            String regNoForPath = StringUtil.nullToEmpty(map.get("path"));
            regNoForPath = java.net.URLDecoder.decode(regNoForPath, "UTF-8");
            //本地路径
            String sysPath = StringUtil.initSysPath();
            String projectPath = sysPath.substring(0, sysPath.length() - 16) + "upload" + "/" + regNoForPath + "/";
            // 定义文件大小的限制值 
            int size = 2;
            // 获取上传文件工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 设置上传工厂的限制
            factory.setSizeThreshold(10 * 1024 * 1024);
            File file = new File(projectPath);
            if (!file.exists()) {
                file.mkdirs();// 建立文件夹
            }
            // 设置上传的路径
            factory.setRepository(file);
            // 根据上传工厂获取servletfileupload对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 设置上传文件的大小
            upload.setSizeMax(size * 1024 * 1024);
            // 设置上传的监听器
            upload.setProgressListener(new ProgressListener() {
                long num = 0;
                public void update(long bytesRead, long contentLength, int items) {
                    long progress = bytesRead * 100 / contentLength;
                    if (progress == num) {
                        return;
                    }
                    num = progress;
                }
            });
            for (Iterator<FileItem> it = fileList.iterator(); it.hasNext();) {
                FileItem item = (FileItem)it.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                } else {
                    // 获取字段的名字
                    String fieldName = item.getFieldName();
                    // 获取文件的路径
                    String fileName = item.getName();
                    // 获取文件的名字可以根据不同的后缀进行处理
                    if (fileName.indexOf("\\") != -1) {
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    }
                    if (fileName.indexOf("/") != -1) {
                        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
                    }
                    //去除所有空格
                    fileName = fileName.replaceAll(" ", "");
                    setFileName(fileName) ;
                    // 取得文件的类型
                    String contentType = item.getContentType();
                    fileUploadPath = projectPath + fileName;
                    // 以当前时间来生成上传的文件名字 
                    fos = new FileOutputStream(fileUploadPath); // 将文件放入路径中
                    // 如果上传文件已经在内存中
                    if (item.isInMemory()) {
                        fos.write(item.get());
                    } else {
                        int len;
                        byte[] buffer = new byte[1024];
                        // 获取文件的输入流
                        is = item.getInputStream();
                        // System.out.println(is.available());
                        while ((len = is.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                        if (null != is)
                            is.close();
                    }

                    if (null != fos)
                        fos.close();
                    // 返回附件路径
                    object.put("url", fileUploadPath);
                }
            }
            object.put("success", true);
            msg = "上传成功";
        } catch ( Exception e ) {
            object.put("success", false);
            if (null == msg)
                msg = "上传失败";
        }  
    	return fileUploadPath;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值