`
fengzhizi715
  • 浏览: 159755 次
  • 性别: Icon_minigender_1
  • 来自: 上海 苏州
社区版块
存档分类
最新评论

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
<p> 演示程序下载地址:<g:link controller="download" action="downloadFile" id="1"><img src="${createLinkTo(dir:'images',file:'download.jpg')}" alt="" width="71" height="30" /></g:link></p>
<p> 演示程序下载次数:${count}</p>


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


这样既实现了文件下载,又实现了统计文件下载次数
分享到:
评论
2 楼 fengzhizi715 2009-11-15  
helian 写道
不错。修改count的代码放到filter会不会有问题?

class MyFilters {
   def filters = {
       downloadCount(controller:'download', action:'downloadFile') {
           after = {
              def file = DownloadFile.findById(params.id)  
              file.setCount(file.count+1)  
              file.save()  
           }
       }
   }
}


这个 我还没试过 有机会试一下 :)
1 楼 helian 2009-11-09  
不错。修改count的代码放到filter会不会有问题?

class MyFilters {
   def filters = {
       downloadCount(controller:'download', action:'downloadFile') {
           after = {
              def file = DownloadFile.findById(params.id)  
              file.setCount(file.count+1)  
              file.save()  
           }
       }
   }
}

相关推荐

Global site tag (gtag.js) - Google Analytics