Java SpringMVC实现文件下载

avatar 2017年09月04日19:23:31 6 2241 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此
这里贴一下主要代码

首先根据id查询从数据库查询文件记录信息



  1. /**
  2.     * 下载
  3.     * @param id 文件ID
  4.     * @param request
  5.     * @param response
  6.     * @throws IOException
  7.     */
  8.    @GetMapping(value = "/attachment/download")
  9.    public void downloadFile(@RequestParam("id") String id,
  10.                             HttpServletRequest request, HttpServletResponse response) throws IOException {
  11.        Attachment attachment = attachmentService.findById(id);
  12.        if (attachment != null) {
  13.            InputStream f = new FileInputStream(new File(attachment.getPath()));
  14.            response.reset();
  15.            response.setContentType("application/x-msdownload;charset=utf-8");
  16.            response.setHeader("Content-Disposition""attachment;filename=" + attachment.getName() + "." + attachment.getSuffix());//下载文件的名称
  17.            ServletOutputStream sout = response.getOutputStream();
  18.            BufferedInputStream bis = null;
  19.            BufferedOutputStream bos = null;
  20.            try {
  21.                bis = new BufferedInputStream(f);
  22.                bos = new BufferedOutputStream(sout);
  23.                byte[] buff = new byte[2048];
  24.                int bytesRead;
  25.                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  26.                    bos.write(buff, 0, bytesRead);
  27.                }
  28.                bos.flush();
  29.                bos.close();
  30.                bis.close();
  31.            } catch (final IOException e) {
  32.                throw e;
  33.            } finally {
  34.                if (bis != null) {
  35.                    bis.close();
  36.                }
  37.                if (bos != null) {
  38.                    bos.close();
  39.                }
  40.            }
  41.        }
  42.    }

在浏览器访问这个请求后,浏览器会弹出下载
  • 微信
  • 交流学习,服务定制
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0