1. 程式人生 > >SpringBoot(三):檔案下載

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>