首页 > 编程语言 > 详细

SpringMVC实现文件下载

时间:2017-01-10 20:05:21      阅读:334      评论:0      收藏:0      [点我收藏+]
<br> public static void download(HttpServletRequest request, 
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception { 
         
        request.setCharacterEncoding("UTF-8"); 
        BufferedInputStream bis = null; 
        BufferedOutputStream bos = null; 
   
        //获取项目根目录
        String ctxPath = request.getSession().getServletContext() 
                .getRealPath(""); 
         
        //获取下载文件露肩
        String downLoadPath = ctxPath+"/uploadFile/"+ storeName; 
   
        //获取文件的长度
        long fileLength = new File(downLoadPath).length(); 
 
        //设置文件输出类型
        response.setContentType("application/octet-stream"); 
        response.setHeader("Content-disposition", "attachment; filename=" 
                + new String(storeName.getBytes("utf-8"), "ISO8859-1"));
        //设置输出长度
        response.setHeader("Content-Length", String.valueOf(fileLength)); 
        //获取输入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath)); 
        //输出流
        bos = new BufferedOutputStream(response.getOutputStream()); 
        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(); 
    } 
技术分享

下载直接访问控制器如:http:\\localhost:8080/springmvc/download.do

 或者通过JSP页面

<a href="./downloadFile/download" >下载</a> 

SpringMVC实现文件下载

原文:http://www.cnblogs.com/hero96/p/6270357.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!