Kindeditor图片上传、服务器端浏览用Groovy实现

贴代码——

 

我已经集成到JStore Desktop for Single的MVC里了,源码和例子请参考我的另一边BLOG,通过SVN下载——/webapp/WEB-INF/gy/tools.gy的后两个方法。

 

写法好简洁啊,比起Kindeditor例子JSP源码。

 

	// kindeditor image upload
	def Map img_json(){
		final String save_url = '/userfiles/'
		final String save_path = AppGlobal.getAppSrc(save_url)
		final int max_size = 1024 * 1024
		List ext_allow = ["gif", "jpg", "jpeg", "png", "bmp"]

		if(!params._files){
			return [output:JsonUtil.toJSON([error:'请选择文件。'])]
		}

		def item = params._files.itemList[0]
		if(item){
			byte[] binary = item.get()
			if(binary.size() > max_size){
				return [output:JsonUtil.toJSON([error:'上传文件大小超过限制。'])]
			}
			String file_ext = item.name.substring(item.name.lastIndexOf(".") + 1).toLowerCase()
			if(!(file_ext in ext_allow)){
				return [output:JsonUtil.toJSON([error:'文件格式不支持。'])] 
			}

			String name = System.currentTimeMillis() + '_' + new Random().nextInt(1000) + "." + file_ext

			try{
				item.write(new File(save_path, name))
			}catch(Exception e){
				return [output:JsonUtil.toJSON([error:'上传文件失败。'])]
			}

			return [output:JsonUtil.toJSON([error:0, url: save_url + name])]
		}

		return [output:JsonUtil.toJSON([error:'请选择文件。'])]
	}

	// kindeditor image file browser
	def Map file_json(){
		// TODO
		// diff save_path by user login
		final String save_url = '/userfiles/'
		final String save_path = AppGlobal.getAppSrc(save_url)
		final int max_size = 1024 * 1024
		List ext_allow = ["gif", "jpg", "jpeg", "png", "bmp"]

		String path = params.path?:''
		String order = params.order?params.order.toLowerCase():'name'
		if (path.indexOf("..") >= 0) 
			return [output:'No Allow.']
		if(path && !path.endsWith('/')) 
			return [output:'Parameter Invalid.']


		String up_dir_path = ''
		if(path){
			String str = path.substring(0, path.length() - 1)
			up_dir_path  = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : ''
		}

		// current directory
		File cf = new File(save_path + path)
		if(!cf.exists() || !cf.isDirectory())
			return [output:'File not exists.']

		List files = []
		SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
		cf.eachFile{
			files << [
				filename: it.name,
				datetime: ff.format(it.lastModified()),
				is_dir: it.isDirectory(), 
				has_file: it.isDirectory() && it.listFiles() != null,
				filesize: it.isFile()?it.length():1L,
				is_photo: it.isFile() && ext_allow.contains(it.name.substring(it.name.lastIndexOf(".") + 1).toLowerCase()),
				filetype: it.isFile()?it.name.substring(it.name.lastIndexOf(".") + 1).toLowerCase():''
			]
		}

		files.sort{
			'name' == order?it.name:('type' == order?it.filetype:it.filesize)
		}

		// return json data
		Map rr = [:]
		rr.moveup_dir_path = up_dir_path
		rr.current_dir_path = path
		rr.current_url = save_url + path
		rr.total_count = files.size()
		rr.file_list = files

		return [output:JsonUtil.toJSON(rr)]
	}
 

你可能感兴趣的:(json,浏览器,SVN,ext,groovy)