# File **Repository Path**: GntLee/File ## Basic Information - **Project Name**: File - **Description**: grails3文件上传小demo - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-11-15 - **Last Updated**: 2020-12-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #Grails 文件上传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,页面内容: