Java传统下载和SpringMVC下载

 1  /**
 2      * 传统下载
 3      * @param filename 文件名称
 4      */
 5     @RequestMapping(value="download", method={RequestMethod.GET, RequestMethod.POST})
 6     public void download(HttpServletRequest request, HttpServletResponse response, String filename) {
 7         String realpath = request.getServletContext().getRealPath("/");
 8         // 输出文件路径
 9         String filepath = realpath + filedir + "/" + filename;
10         response.setContentType("application/octet-stream;charset=utf-8");
11         response.setHeader("Content-Disposition", "attachment;filename=" + filename);
12         response.addHeader("Pragma", "no-cache");
13         response.addHeader("Cache-Control", "no-cache");
14         try {
15             OutputStream os = response.getOutputStream();
16             InputStream is = new BufferedInputStream(new FileInputStream(filepath));
17             byte[] buffer = new byte[4096];
18             int length = 0;
19             while((length = is.read(buffer)) > 0) {
20                 os.write(buffer, 0, length);
21             }
22             is.close();
23             os.close();
24         } catch (Exception e) {
25             e.printStackTrace();
26         }
27     }
28 
29     /**
30      * SpringMVC下载
31      * @return 文件名称
32      */
33     @RequestMapping(value="graceDownload", method={RequestMethod.GET, RequestMethod.POST})
34     public ResponseEntity<byte[]> graceDownload(HttpServletRequest request, String filename) {
35         String realpath = request.getServletContext().getRealPath("/");
36         // 输出文件路径
37         String filepath = realpath + filedir + "/" + filename;
38         byte[] byteArray = null;
39         try {
40             byteArray = FileUtils.readFileToByteArray(new File(filepath));
41         } catch(Exception e) {
42             e.printStackTrace();
43         }
44         HttpHeaders headers = new HttpHeaders();
45         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
46         headers.setContentDispositionFormData("attachment", filename);
47         ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(byteArray, headers, HttpStatus.CREATED);
48         return responseEntity;
49     }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值