---
title: "Grails使用kindeditor，支持附件"
author: "rox"
date: "2011-07-21T00:25:51Z"
tags: []
categories: ["互联网"]
slug: "grails-kindeditor"
draft: false
lastmod: "2011-07-24T15:30:41Z"
id: 1129290
url: "https://rox.iteye.com/blog/1129290"
---

1、将附件 **grails-kindeditor.rar** 带目录解压到web-app目录

2、gsp文件代码：

 

```
<head>
<script charset="utf-8" src="${resource(dir: 'kindeditor', file: 'kindeditor.js')}"></script>
<script>
    KE.show({
        id : 'repost_content',
        resizeMode : 1,
        allowPreviewEmoticons : false,
        allowUpload : true,
        imageUploadJson : '${createLink(action:'uploadimagejson')}',
        attachUploadJson : '${createLink(action:'uploadattachjson')}',
        items : [
            'fontname', 'fontsize', '|', 'textcolor', 'bgcolor', 'bold', 'italic', 'underline',
            'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
            'insertunorderedlist', '|', 'emoticons', 'image', 'attach', 'flash', 'link']
    });
</script>
</head>
<body>
<g:textArea id="repost_content" name="content" rows="500" cols="400"/>
</body>
```

 

 

3、action代码：

 

本来是使用对象封装了文件部分属性，这里假定Attach对象有originalName属性，再使用最简单的saveFile,getFile闭包实现

 

```
    import grails.converters.JSON

    def uploadattachjson = {
        def text = [error: 1, message: '请选择文件。'] as JSON
        if (params.attachFile) {
            def attach = savePic(params.attachFile)
            text =  [error: 0, url: createLink(action: 'downattach', id: attach.id)] as JSON
        }

        render(contentType: 'text/html; charset=UTF-8', text: text)
    }

    def downattach = {
        def attach = getFile(params.id)
        if (attach.exists()) {
            response.setContentType("application/octet-stream")
            response.setHeader("Content-disposition", "attachment;filename=${getFileName(attach.originalFilename)}" )
            response.setContentLength(attach.length() as int)
            response.outputStream.write(attach.bytes)
        } else {
            response.sendError(404)
        }

    }

    def getFileName = {
        String agent = request.getHeader('USER-AGENT')
        if (null != agent && -1 != agent.indexOf('MSIE')) {
            URLEncoder.encode(it, 'UTF8')
        } else {
            MimeUtility.encodeText(it, 'UTF8', 'B')
        }
    }

    def saveFile = {
        def attach = new Attach()
        attach.originalName = it.originalFilename

        it.transferTo(
            new File('c:\attach\'+it.originalFilename)
        )
        attach.save()
    }

    def getFile = {
        def attach = Attach.get(it)
        new File('c:\attach\'+attach.originalName)
    }
```