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();
    }
}

 

 

 

 

 

posted @ 2020-03-23 11:31  山河已无恙  阅读(2711)  评论(0编辑  收藏  举报