• 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();
        }
  • 相关阅读:
    contentSize、contentInset和contentOffset区别 分类: iphone开发
    iOS设计模式——Category
    如何更好地限制一个UITextField的输入长度
    UIApplication sharedApplication详细解释-IOS
    IOS --- 对象归档
    iOS 数据持久化之使用NSUserDefaults存储数据
    判断素数 一个数的约数 一个整数的幂次约分
    埃氏筛法
    双六(扩展欧几里得算法)
    矩阵快速幂 模板
  • 原文地址:https://www.cnblogs.com/yjtx/p/4442245.html
Copyright © 2020-2023  润新知