grails中实现文件下载并统计文件下载次数

controller的代码如下:
该类负责下载文件以及统计文件的下载次数
class DownloadController {

def downloadFile = {
def id = params.id
response.setHeader("Content-disposition", "attachment; filename=TheSalesDemo.rar")
response.contentType = "application/x-rarx-rar-compressed"
def filepath = "TheSalesDemo.rar"
def out = response.outputStream
def inputStream = new FileInputStream(filepath)
byte[] buffer = new byte[1024]
int i = -1
while ((i = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, i)
}
def file = DownloadFile.findById(id)
file.setCount(file.count+1)
file.save()
out.flush()
out.close()
inputStream.close()
}

}



首页调用的gsp代码 主要是调用download控制器的downloadFile这个action

演示程序下载地址:


演示程序下载次数:${count}



下面的代码主要用于首页的action中,显示统计次数
 def count = downloadFile.getCount()
[[count:count]


这样既实现了文件下载,又实现了统计文件下载次数 :D

你可能感兴趣的:(Grails,Java,Groovy,on,Grails)