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

SpringBoot(三):文件下载

时间:2018-07-03 18:14:30      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:red   stat   mapping   puts   div   tput   test   Servle   void   

SpringBoot(三):文件下载

在原来的SpringBoot–uploadfile项目基础上添加文件下载的Controller:

 @RequestMapping(value = "/testDownload", method = RequestMethod.GET)
        public void Download(HttpServletResponse res) {
          String fileName = "1.png";
          res.setHeader("content-type", "application/octet-stream");
          res.setContentType("application/octet-stream");
          res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
          byte[] buff = new byte[1024];
          BufferedInputStream bis = null;
          OutputStream os = null;
          try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File("d://"
                + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
              os.write(buff, 0, buff.length);
              os.flush();
              i = bis.read(buff);
            }
          } catch (IOException e) {
            e.printStackTrace();
          } finally {
            if (bis != null) {
              try {
                bis.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          System.out.println("success");
        }

 

需要下载的文件放在D盘。

 @RequestMapping(value = "/download", method = RequestMethod.GET)
     public String Download() {
         return "/fileDownload";
     }

 

fileDownload.html:

<html>
<head>
<meta charset="UTF-8"/>
<title>文件下载示例</title>
</head>
<body>
    <h2>文件下载示例</h2>
    <hr/>
    <a href="/testDownload">下载</a>
</body>
</html>

 

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26641781/article/details/76572422

SpringBoot(三):文件下载

标签:red   stat   mapping   puts   div   tput   test   Servle   void   

原文地址:https://www.cnblogs.com/hfultrastrong/p/9259696.html

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