//1.controller
package com.xdth
class UploadController {
def index() {
render(view:"../index")
}
/**
* 文件上传
* @return
*/
def upload(){
/*定义文件上传基本目录*/
def path = "/upload"
def basePath = request.getSession().getServletContext().getRealPath(path)
//检查upload是否存在
File saveFile = new File(basePath)
if(!saveFile.exists()){
saveFile.mkdirs()
}
def description = params["description"]
def file = request.getFile("myFile")
//上传文件原文件名
def oldName = file.getOriginalFilename()
if(file){
//用时间戳作为新文件名
def newName = System.currentTimeMillis()+oldName.substring(oldName.lastIndexOf(".",oldName.length()-1))
//上传文件开始
file.transferTo(new File(basePath+File.separator+newName))
Upload upload = new Upload(oldName,newName,basePath,description)
upload.save()
}
flash.message = "${oldName} 上传成功!"
//从一个action跳转到另一个action
redirect action:"show",model: [params:params]
}
/**
* 文件下载
* @return
*/
def download(){
def upload = Upload.findById(params.id)
//File.separator根据当前系统自动获取盘符
def downloadPath = upload.filePath+File.separator+upload.newName
def file_name = upload.newName
def bis = new BufferedInputStream(new FileInputStream(downloadPath))
def bos = new BufferedOutputStream(response.outputStream)
long fileLength = new File(downloadPath).length()
response.setCharacterEncoding("UTF-8")
response.setContentType("multipart/form-data")
String userAgent = request.getHeader("User-Agent").toLowerCase()
if (userAgent.contains("msie") || userAgent.contains("like gecko"))
{
// win10 ie edge 浏览器 和其他系统的ie
file_name = URLEncoder.encode(file_name, "UTF-8")
}
else
{
file_name = new String(file_name.getBytes("UTF-8"), "iso-8859-1")
}
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", file_name))
response.setHeader("Content-Length", String.valueOf(fileLength))
byte[] buff = new byte[2048]
int bytesRead
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead)
}
bis.close()
bos.close()
}
/**
* 全部文件查看
* @return
*/
def show(){
def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
def offset = params.offset ? params.offset.toInteger() : 0
def queryList = Upload.executeQuery("from Upload",[max:max,offset:offset]).asList()
respond queryList,view: "show",model: [queryList:queryList,params:params,count:queryList.size()]
}
}
2.index.gsp
文件描述:
查看全部文件
3.show.gsp
返回