• SpringMVC 文件下载


    第一种方法使用 HttpMessageConverter 下的 ResponseEntity<> 实现。

    @RequestMapping("/testHttpMessageDown")
        public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{
             String filename = "123.jpg";
                //根据不同浏览器处理下载时文件名乱码问题
                if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
                    filename = URLEncoder.encode(filename, "UTF-8");  
                } else {  
                    filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");  
                }
            byte[] body = null;
            InputStream is = request.getSession().getServletContext().getResourceAsStream("/upload/user/JSON.jpg");
            body = new byte[is.available()];
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attchement;filename=" + filename);
            HttpStatus statusCode = HttpStatus.OK;
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
            return entity;
        }

    第二种方法是常用的文件下载方式

    @RequestMapping("/testFileDown")
        public void fileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException{
            String filename = "这是中文名称123abc()()-234十几分.pdf";
            //根据不同浏览器处理下载时文件名乱码问题
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
                filename = URLEncoder.encode(filename, "UTF-8");  
            } else {  
                filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");  
            }
    //        response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;fileName="+filename);
            InputStream is = request.getSession().getServletContext().getResourceAsStream("/upload/中文名称的文件名.pdf");
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length = 0;
            while((length = is.read(b)) > 0){
                os.write(b);
            }
            os.flush();
            os.close();
            is.close();
        }
  • 相关阅读:
    python zip()与zip(*ziped)以及list(zip(a,b))
    通信原理(第七版)-樊昌信-第一章-绪论-重要知识点
    通信原理-自相关与互相关函数的关系
    通信原理(第七版)-樊昌信-第二章-确知信号-重要知识点
    C#Linq的10个练习
    C#从委托、lambda表达式到linq总结
    C#的隐式类型、匿名类型、自动属性、初始化器
    MVC开发之Razor的使用
    Markdown常用语法
    MVC开发之注入容器Ninject的使用
  • 原文地址:https://www.cnblogs.com/yjtx/p/4442245.html
Copyright © 2020-2023  润新知