其他分享
首页 > 其他分享> > springboot下载文件

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

 

标签:文件,outputStream,springboot,response,file,download,fileName,final,下载
来源: https://www.cnblogs.com/txt1024/p/15795920.html