码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC 文件下载

时间:2015-04-20 18:14:15      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

第一种方法使用 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/user/中文名称的文件名.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();
    }

 

SpringMVC 文件下载

标签:

原文地址:http://www.cnblogs.com/yjtx/p/4442245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!