Kindeditor画像アップロード、サーバ側ブラウズ用Groovy実現


コードを貼る--
 
Jstore Desktop for SingleのMVCに統合しました.ソースコードと例は私の反対側のBLOGを参考にして、SVNでダウンロードしてください./webapp/WEB-INF/gy/tools.gyの後の2つの方法.
 
書き方は簡潔ですね、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)]
	}