grails文件下载

来源:互联网 发布:矩阵求导链式法则 编辑:程序博客网 时间:2024/05/20 23:55
1.后台controller代码

[java] view plain copy print?
  1. /** 
  2.     * 文件下载 
  3.     */  
  4.   def fileDownload = {  
  5.     def filePath = params.filePath  //文件路径  
  6.     def fileName = encode(params.fileName)  //文件名  
  7.     response.setHeader("Content-disposition""attachment; filename=" + fileName)  
  8.     response.contentType = "application/x-rarx-rar-compressed"  
  9.     def out = response.outputStream  
  10.     def inputStream = new FileInputStream(filePath)  
  11.     byte[] buffer = new byte[1024]  
  12.     int i = -1  
  13.     while ((i = inputStream.read(buffer)) != -1) {  
  14.         out.write(buffer, 0, i)  
  15.     }  
  16.     out.flush()  
  17.     out.close()  
  18.     inputStream.close()  
  19.   }  
  20.   
  21.   /** 
  22.    * 字符编码 
  23.    */  
  24.    final def encode(String value,String charSet='UTF-8'){  
  25.        java.net.URLEncoder.encode(value, charSet)  
  26.    }  


 

2.前端gsp

[plain] view plain copy print?
  1. /**  
  2.  *下载  
  3.  */  
  4.  function download(m,f){  
  5.   //检查文件是否存在  
  6.   var checkurl ="${contextPath}/fileUpload/checkFileExists?filePath="+encodeURIComponent(f);  
  7.   j.ajax({  
  8.    url:checkurl,  
  9.    async:false,  
  10.    success:function (dt) {  
  11.     json = eval('('+dt+')');  
  12.     if(json.success){  
  13.      var url= "${contextPath}/fileUpload/fileDownload?filePath="+encodeURIComponent(f)+"&fileName="+encodeURIComponent(m);  
  14.      window.open(url);  
  15.      return false;  
  16.     }else{  
  17.      alert(json.msg);  
  18.     }  
  19.    }  
  20.   });  
  21.  } 
原创粉丝点击