springboot下载文件

如下:

@GetMapping("download")
public String abc(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
  final String fileName = request.getParameter("fileName");
  if (!StringUtils.isEmpty(fileName)) {
    // 下载
    final File file = new File(path, fileName);
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
    response.setContentType("application/octet-stream");
    try (final ServletOutputStream outputStream = response.getOutputStream()){
      Files.copy(Paths.get(file.getPath()), outputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return null;
}

 

浏览器访问即可下载文件

http://127.0.0.1:8080/download?fileName=aaa.txt

 

上一篇:安装centos7 报错[FAILED] Failed to start Switch Root. see 'systemctl status initrd-switch-root.service' for details


下一篇:Java并发编程的艺术(七)——Executors