springboot实现下载附件

2022-05-28 09:35:33 浏览数 (1)

目录

  • 1 controller层
  • 2 Service层

springboot实现下载附件

1 controller层

代码语言:javascript复制
  public R fjxz(String bh){
      
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            xzServcie.xz(bh,response);
            return R.ok();
       
    }

2 Service层

import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils;

代码语言:javascript复制
  @Override
    public void xz(String bh, HttpServletResponse response) throws Exception {
       
        String url = "http://"
        String mc="文件名称"
        FileInputStream inputStream = new FileInputStream(new File(url,mc));
      
        //附件下载
        response.setHeader("Content-Disposition","attachment;filename="  URLEncoder.encode(“标题”,"UTF-8"));

        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(inputStream, outputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }

0 人点赞