zoukankan      html  css  js  c++  java
  • SpringMVC实现文件下载

    <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> 
  • 相关阅读:
    ThreadLocal
    贪心算法
    KMP
    多线程设计模式
    String 为什么是不可变的
    6-Ubuntu—截屏与截取选定区域
    5-Ubuntu—查看进程并关闭进程
    4-python基础—查看模块所在位置(适应于任何操作系统)
    4-Ubuntu—终端下重启与关机
    3-python基础—enumerate()
  • 原文地址:https://www.cnblogs.com/hero96/p/6270357.html
Copyright © 2011-2022 走看看