springMVC+freemarker运行KindEditor插件

我把图片保存在根目录下,自己写了一个方法获得图片。


1.js代码处理

<script>
	var editor;
	KindEditor.ready(function(K) {
		var options = {
			filterMode : true,
			afterChange : function() {
				K('.word_count1').html(this.count());
				K('.word_count2').html(this.count('text'));
			},
			uploadJson : '/svc/marketing/emailMarketing.htm?method=upload',
            allowFileManager : false,
            allowFlashUpload :false,
            allowMediaUpload : false,
            allowFileUpload :false 
		};
		editor = K.create('textarea[name="emailContent"]', options);
	});

	function emailPopUp(){
		var subject = $.trim($('#subject').val());
		if(subject == ''){
			alert('主题不能为空!');
			return 
		}
		if(editor.isEmpty()){
			alert('请填写邮件内容!');
			return
		}
		// 取得HTML内容
		var html = editor.html();
		// 同步数据后可以直接取得textarea的value
		editor.sync();
		$('#mainForm').submit();
	}

</script>

2.Controller代码处理

	
	/**
	 * KindEditor文件上传
	 * @param request
	 * @param response
	 * @param model
	 * @param session
	 * @throws JSONException
	 * @throws FileUploadException
	 */
	@RequestMapping(params = "method=upload")
	public void upload(HttpServletRequest request,HttpServletResponse response, ModelMap model, HttpSession session) throws JSONException, FileUploadException {	
		String merchantId = session.getAttribute("machantId").toString();	//商户的Id
		//文件保存目录路径
		String savePath = "/opt/pay/svc/upload/attached/";
		//取图片的连接
		String getImageUrl  = "/svc/marketing/emailMarketing.htm?method=getImage";
		
		//定义允许上传的文件扩展名
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");

		//最大文件大小
		long maxSize = 1000000;
	
		if(!ServletFileUpload.isMultipartContent(request)){
			writeMsg(response, "请选择文件。");
			return;
		}
		//检查目录
		File uploadDir = new File(savePath);
		if(!uploadDir.isDirectory()){
			writeMsg(response, "上传目录不存在。");
			return;
		}
		//检查目录写权限
		if(!uploadDir.canWrite()){
			writeMsg(response, "上传目录没有写权限。");
			return;
		}

		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		if(!extMap.containsKey(dirName)){
			writeMsg(response, "目录名不正确。");
			return;
		}
		
		//创建文件夹,加上商户的Id
		savePath += dirName + "/"+merchantId+"/";
		getImageUrl += "&dirName="+dirName + "/"+merchantId+"/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		//加上年月日
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		getImageUrl += "&date="+ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		
		DefaultMultipartHttpServletRequest mrequest= (DefaultMultipartHttpServletRequest)request;
		Map map=mrequest.getFileMap();
		Collection<MultipartFile> collection = map.values();
		Iterator it = collection.iterator();
		
		while (it.hasNext()) {
			CommonsMultipartFile file=(CommonsMultipartFile) it.next();
			if(!file.isEmpty()){
			long fileSize = file.getSize();		//文件大小
			String fileName = file.getOriginalFilename();	//文件名
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();	//文件后缀
			    
			if(fileSize > maxSize){
				writeMsg(response,"上传文件大小超过限制100M。");
				return;
			}
			if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
				writeMsg(response,"上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
				return;
			}
			 
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			 
			try{
				File uploadedFile = new File(savePath, newFileName);
				file.transferTo(uploadedFile);  
			}catch(Exception e){
				writeMsg(response, "上传文件失败。");
				return;	   
			}
			JSONObject obj = new JSONObject();
			obj.put("error", 0);
			obj.put("url", getImageUrl +"&imageName="+ newFileName);
			this.writeJson(response, obj.toString());
			}
		}
		
	}
	
	/**
	 * 输出信息
	 * @param response
	 * @param message
	 * @throws JSONException
	 */
	private void writeMsg(HttpServletResponse response, String message) throws JSONException{
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		this.writeJson(response, obj.toString());
	}
	
	/**
	 * 输出json
	 * @param response
	 * @param msg
	 */
	private void writeJson(HttpServletResponse response, String msg){
		/************以下是解决避免ie下载文件 start*************/
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setContentType("text/html");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.println(msg);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (writer != null) {
				writer.close();
			}
		}	
		/************以下是解决避免ie下载文件 end*************/
	 }

	@RequestMapping(params = "method=getImage", method = RequestMethod.GET)
	public void getImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		OutputStream out = response.getOutputStream();
		AffineTransform transform = new AffineTransform();
		try {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.addHeader("Cache-Control", "no-cache");
			response.setContentType("image/jpeg");
			
			String dirName = (String) request.getParameter("dirName");
			String date = (String) request.getParameter("date");
			String imageName = (String) request.getParameter("imageName");
			
			String imageUrl = "/opt/pay/svc/upload/attached/";
			imageUrl += dirName + date + imageName;
			BufferedImage bis = null;		
			bis = ImageIO.read(new File(imageUrl));// 读取历史上传文件
			
			int w = bis.getWidth();
			int h = bis.getHeight();

			double sx =  1d;
			double sy =  1d;

			transform.setToScale(sx, sy);
			AffineTransformOp ato = new AffineTransformOp(transform, null);

			if (imageUrl != null && imageUrl.contains("png")) {
				ImageIO.write(bis, "PNG", out);
			} else {
				BufferedImage bid = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
				ato.filter(bis, bid);
				ImageIO.write(bid, "jpeg", out);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null)
				out.close();
		}
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值