Grails3文件上传小demo

手把手教你用grails3轻松实现文件上传功能,前端插件layui

创建项目,然后在build.gradle中引入:

compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.3'
compile group: 'commons-io', name: 'commons-io', version: '2.5'

创建一个名为FileResource的域类(domain),用来保存文件信息

package com.system

/**
 * 文件资源
 */
class FileResource {

    //文件编号
    String uuid

    //原文件名
    String oldName

    //新文件名
    String newName

    //相对路径
    String relPath

    //绝对路径
    String absolutePath

    FileResource(String oldName, String newName, String relPath, String absolutePath) {
        this.uuid = UUID.randomUUID().toString()
        this.oldName = oldName
        this.newName = newName
        this.relPath = relPath
        this.absolutePath = absolutePath
    }

    static constraints = {

        uuid unique: true

    }

    static mapping = {
        version false
    }

    def beforeInsert() {
        uuid = UUID.randomUUID().toString()
    }
}

创建UploadController类

package com.system

import grails.converters.JSON
import grails.transaction.Transactional

class UploadController {

    def index() {

    }

    @Transactional
    def upload() {

        def info = [result:false,msg: "文件上传失败!"]

        try {

            def file = request.getFile("file")

            //原文件名
            String oldName = file.getOriginalFilename()

            //用时间戳作为新文件名
            String newName = System.currentTimeMillis()+oldName.substring(oldName.lastIndexOf(".",oldName.length()-1))

            //文件保存相对路径
            String path = "/upload"

            //文件保存绝对路径
            String dirPath = request.getSession().getServletContext().getRealPath(path)

            File saveFile = new File(dirPath)
            if(!saveFile.exists()){
                saveFile.mkdirs()
            }
            if(file){
                //上传文件
                file.transferTo(new File(dirPath + File.separator + newName))
                //文件上传成功后,文件信息录入文件信息表
                FileResource fr = new FileResource(oldName,newName,path,dirPath)
                fr.save(failOnError:true,flash:true)
                info.result = true
                info.msg = "文件上传成功!"
            }
        } catch (e) {
            log.error("文件上传失败,errorMsg={}",e)
        }
        //返回json
        render info as JSON
    }
}

我这里文件上传插件用的layui2.0的,请到layui官网:http://www.layui.com/ 自行下载,也可以用其他上传插件 下载后,复制里面的layui到grails-app/assets/javascripts下面,目录结构如下:

├─grails-app
│  ├─assets
│  │  ├─images
│  │  │  └─skin
│  │  ├─javascripts
│  │  │  └─layui
│  │  │      ├─css
│  │  │      │  └─modules
│  │  │      │      ├─laydate
│  │  │      │      │  └─default
│  │  │      │      └─layer
│  │  │      │          └─default
│  │  │      ├─font
│  │  │      ├─images
│  │  │      │  └─face
│  │  │      └─lay
│  │  │          └─modules
│  │  └─stylesheets

在grails-app/views下面创建upload/index.gsp,页面内容:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>upload模块快速使用</title>
    <asset:stylesheet href="layui/css/layui.css"/>
</head>
<body>

<button type="button" class="layui-btn" id="fileUpload">
    <i class="layui-icon">&#xe67c;</i>上传图片
</button>

<asset:javascript src="layui/layui.js"/>
<script>
    layui.use(['upload', 'layer'], function(){
        var upload = layui.upload;
        var layer = layui.layer;

        //执行实例
        var uploadInst = upload.render({
            elem: '#fileUpload' //绑定元素
            ,url: '${createLink(controller: "upload", action: "upload")}' //上传接口
            ,done: function(res){
                //上传完毕回调
                layer.msg(res.msg);
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });
</script>
</body>
</html>

在grails-app/conf/application.yml最后面配置grails文件上传限制大小(200M):

---
grails:
    controllers:
        upload:
            maxFileSize: 2000000
            maxRequestSize: 2000000

到此配置已经ok,启动项目,访问:http://localhost:8080/upload/index 进行测试

注意事项:

1、如果不配置文件上传大小限制,默认限制大小为128kb,超过就会报错
2、页面引入js和css方式最好用:
    <asset:stylesheet href="xxx.css"/>
    <asset:stylesheet src="xxx.js"/>
且一般css放head里面,js放</body>前面
  • 发表于 2017-11-15 12:46
  • 阅读 ( 3534 )
  • 分类:grails

2 条评论

请先 登录 后评论
不写代码的码农
Jonny

程序猿

65 篇文章

作家榜 »

  1. 威猛的小站长 124 文章
  2. Jonny 65 文章
  3. 江南烟雨 36 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 22 文章
  8. Alan 14 文章