Grails3文件上传小demo

创建项目,然后在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,页面内容:




   
   upload模块快速使用
   










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

---

grails:

controllers:

upload:

maxFileSize: 2000000

maxRequestSize: 2000000```

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

注意事项:

1、如果不配置文件上传大小限制,默认限制大小为128kb,超过就会报错

2、页面引入js和css方式最好用:





且一般css放head里面,js放前面

你可能感兴趣的:(Grails3文件上传小demo)