KindEditor简单版实战(1)图片本地上传

  • 项目需求是:为整个项目提供帮助信息,开始打算是用lucene,后来确定直接查库。方便更改,按我的意思就是lucene,按索引查询是很强大的,而且项目模块是不容易改动的,所以根据模块而提取出来的帮助信息也是不常动的。但是这一切也不是我说了算。唠叨唠叨算了。先给个图片吧,是个简单版的。
  • 下面开始:
  • 首先页面部分jsp:首先加入下面这段,就是内容输入框。
    <textarea id="editor_id" name="content" style="width:700px;height:200px;visibility:hidden;"></textarea>
  • js部分:
    <script>
    	//kindeditor官网:http://kindeditor.net/
    	var editor;
    	KindEditor.ready(function(K) {
    		editor = K.create('textarea[name="content"]', {
    			resizeType : 1,//2或1或0,2时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动。(数据类型:Int,默认值:2)
    			allowPreviewEmoticons : false,//true时鼠标放在表情上可以预览表情。
    			allowImageUpload : true,//true时显示本地上传
    			uploadJson : 'uploadImgHelpConf.action',
    			items : [
    				'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
    				'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
    				'insertunorderedlist', '|', 'emoticons', 'image', 'link']
    		});
    	});
    
    	
    	/*
    	 * 保存
    	 */	
    	function save(){
    		var html = editor.html();//文章内容
    		editor.sync();
    		html = $("#editor_id").val();
    		var title_ = $("#titleId").val();//文章标题
    		var mod_list = $("#mod_list").val();//模块名称
    		var key_word = $("#key_word").val();//关键字
    		
    	    jQuery.post(
    		    	"addHelpConf.action", 
    			    {
    		    		tits : title_,
    		    		modName : mod_list,
    		    		keyWord : key_word,
    		    		context_ : html
    				},
    		     	function(data) {	
    					window.location.href = 'indexHelpConf.action';
    			  	}	      
    		    );	
    	}
    
    </script>

  • 需要引入的:
        <!-- KindEditor:start -->
        <link rel="stylesheet" href="../../kindEditor/themes/default/default.css" />
    	<script charset="utf-8" src="../../kindEditor/kindeditor-min.js"></script>
    	<script charset="utf-8" src="../../kindEditor/lang/zh_CN.js"></script>
    	<!-- KindEditor:end -->

  • 那么uploadJson对应的action是什么呢,下面贴上:
    	/**
    	 * @title :kindEditor插件上传图片
    	 * @Description :
    	 * @data :2014-5-21下午05:37:55
    	 */
    	public String uploadImg() {
    
    	        response.setContentType("text/html; charset=UTF-8");
    	        // 文件保存目录路径
    	        String savePath = ServletActionContext.getServletContext().getRealPath("/") + "attached/";
    	        // 文件保存目录URL
    	        String saveUrl = request.getContextPath() + "/attached/";
    	        // 定义允许上传的文件扩展名
    	        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
    	        // 最大文件大小
    	        long maxSize = Long.parseLong(FileAuditConfUtil.getProperty("max_size"));
    	        PrintWriter out = null;
    	        try {
    	            out = response.getWriter();
    	        } catch (IOException e1) {
    	            logger.error(e1);
    	        }
    
    	        if (imgFile == null) {
    	            out.println(getError("请选择文件。"));
    	            return null;
    	        }
    
    	        // 检查目录
    	        File uploadDir = new File(savePath);
    	        if (!uploadDir.isDirectory()) {
    	            out.println(getError("上传目录不存在。"));
    	            return null;
    	        }
    	        // 检查目录写权限
    	        if (!uploadDir.canWrite()) {
    	            out.println(getError("上传目录没有写权限。"));
    	            return null;
    	        }
    	        // 创建文件夹
    	        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();
    	        }
    	        String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();
    	        if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
    	            out.println(getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。"));
    	            return null;
    	        }
    //	        if (imgFile.length() > maxSize) {
    //	            out.println(getError("[ " + imgFileFileName + " ]超过单个文件大小限制,文件大小[ " + imgFile.length() + " ],限制为[ " + maxSize + " ] "));
    //	            return null;
    //	        }
    	        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    	        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
    	        File uploadedFile = new File(savePath, newFileName);
    	        try {
    	            FileUtil.copyFile(imgFile, uploadedFile);//zhanghubiao
    	            JSONObject obj = new JSONObject();
    	            obj.put("error", 0);
    	            obj.put("url", saveUrl + newFileName);
    	            logger.debug(obj);
    	            out.println(obj.toString());
    	            logger.debug("上传图片:[" + uploadedFile.getName() + "]" + ">>>[" + newFileName + "]成功");
    	        } catch (IOException e) {
    	            logger.error("图片上传失败:" + e);
    	        }
    	        return null;
    	    }
    	
    	    private String getError(String message) {
    	        JSONObject obj = new JSONObject();
    	        obj.put("error", 1);
    	        obj.put("message", message);
    	        logger.debug(obj);
    	        return obj.toString();
    	    }

    方法里的参数呢:
    	/**
    	 * 添加文章的时候图片上传相关
    	 */
        private File imgFile;
        /**
         * 文件名称
         */
        private String imgFileFileName;
    
        /**
         * 图片宽度
         */
        private String imgWidth;
    
        /**
         * 图片高度
         */
        private String imgHeight;
    
        /**
         * 图片对齐方式
         */
        private String align;
    
        /**
         * 图片标题
         */
        private String imgTitle;

    别忘记set,get哦!
  • 还有一个类是获取配置文件的:
    package com.dts.conf;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class FileAuditConfUtil {
    	
    	private static Properties prop = null;
    	private static String path;
    	static {
    		try {
    			path = "../../../config/file_audit.properties";
    			prop = new Properties();
    			prop.load(FileAuditConfUtil.class.getResourceAsStream(path));			
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public static String getProperty(String key) {
    		return prop.getProperty(key);
    	}
    	
    	public static String getProperty(String key, String defaultValue) {
    		String val = prop.getProperty(key);
    		return val != null ? val : defaultValue;
    	}
    	
    	public static void setProperty(String key,String value){
    		
    		try{
    			prop.setProperty(key, value);  
    			// 文件输出流  
    			FileOutputStream fos = new FileOutputStream(FileAuditConfUtil.class.getResource("/").getPath()+"config/file_audit.properties");
    			// 将Properties集合保存到流中  
    			prop.store(fos, "Copyright (c) tongtech.com");  
    			fos.close();// 关闭流
    		
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    }
    

    方法里的setProperty这里没用,不过项目里有修改配置文件的部分,这里就不删除了。如果使用可以删除。
  • 还有FileUtil类:
    package com.tongtech.cloud.platform.util;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    
    public class FileUtil {
    	
    	public static final String NEW_LINE = System.getProperty("line.separator");
    
    	public static final void copyFile(File inputFile, File outputFile) throws IOException {
    		if(inputFile == null) {
    			throw new IllegalArgumentException("Input file is null");
    		}
    		if(outputFile == null) {
    			throw new IllegalArgumentException("Output file is null");
    		}
    		
    		InputStream is = null;
    		OutputStream os = null;
    		try {
    			is = new FileInputStream(inputFile);
    			os = new FileOutputStream(outputFile);
    			copyFile(is, os);
    		} finally {
    			if(os != null) {
    				try {
    					os.close();
    				} catch (Exception e) {
    					
    				}
    			}
    			if(is != null) {
    				try {
    					is.close();
    				} catch (Exception e) {
    					
    				}
    			}
    		}
    	}
    
    	public static final void copyFile(InputStream is, OutputStream os) throws IOException {
    		if(is == null) {
    			throw new IllegalArgumentException("Input stream is null");
    		}
    		if(os == null) {
    			throw new IllegalArgumentException("Output stream is null");
    		}
    		
    		byte buffer[] = new byte[8192];
    		int count = -1;
    		while ((count = is.read(buffer)) != -1) {
    			os.write(buffer, 0, count);
    		}
    	}
    	
    	public static final String getFileContent(String path) throws FileNotFoundException {
    		return getFileContent(new FileInputStream(new File(path)));
    	}
    	
    	public static final String getFileContent(InputStream is) {
    		StringBuilder sb = new StringBuilder();
    
    		BufferedReader reader = null;
    		try {
    			reader = new BufferedReader(new InputStreamReader(is));
    			String tempString = null;
    			boolean first = true;
    			while ((tempString = reader.readLine()) != null) {
    				if(!first) {
    					sb.append(NEW_LINE);
    				}
    				first = false;
    				
    				sb.append(tempString);
    			}
    			reader.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (reader != null) {
    				try {
    					reader.close();
    				} catch (IOException e1) {
    				}
    			}
    		}
    		
    		return sb.toString();
    	}
    	
    	public static final void createFile(OutputStream out,String fileContent){
    		PrintWriter pw = null;
    		pw = new PrintWriter(out);
    		pw.println(fileContent);
    		pw.flush();
    		pw.close();
    	}
    }
    

  • 为什么要返回json呢,因为要返回固定的json,插件才可以分析呈现。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值