zoukankan      html  css  js  c++  java
  • Spring文件下载方式整理

    项目中遇到文件下载,所以总结一下遇到的文件下载方式:

    方法一,返回一个 ResponseEntity,响应实体返回一个字节数组,

     public ResponseEntity<byte[]> exportData() throws IOException {
    
            HttpHeaders headers=new HttpHeaders();
            headers.setContentDispositionFormData("attachment", new File(filePath).getName());
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filePath)),headers, HttpStatus.CREATED);
        }

     ResponseEntity用于构造标识整个http响应:状态码、头部信息以及相应体内容。因此我们可以使用其对http响应实现完整配置。

     

     方法二,通过向响应对象中写入字符流的方式实现。

     protected void service(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/octet-stream");
           
            resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("中国", "utf-8")+".txt");
            PrintWriter os = resp.getWriter();
            String path = this.getServletContext().getRealPath("/download");
            Reader is = new BufferedReader(new FileReader(new File(path,"t.txt")));
            int len=0;
            char[] buffer = new char[200];
            while((len=is.read(buffer))!=-1){
                os.print(new String(buffer,0,len));
            }
            is.close();
            os.close();
        }
    }

     

     

  • 相关阅读:
    POJ1239
    HDU 2829 四边形不等式优化
    返回数字二进制的最高位位数o(n)
    矩阵快速幂 模板
    HDU4718 The LCIS on the Tree(LCT)
    HDU4010 Query on The Trees(LCT)
    HDU3487 Play With Chains(Splay)
    CF444C DZY Loves Colors
    HDU4836 The Query on the Tree(树状数组&&LCA)
    HDU4831&&4832&&4834
  • 原文地址:https://www.cnblogs.com/liruilong/p/12515542.html
Copyright © 2011-2022 走看看