spring实现文件下载的方法是什么

avatar
作者
筋斗云
阅读量:0

在Spring中实现文件下载可以使用以下方法:

  1. 使用 ResponseEntity 返回文件流:
@GetMapping("/downloadFile") public ResponseEntity downloadFile() {     Resource resource = new FileSystemResource("path/to/file.txt");          HttpHeaders headers = new HttpHeaders();     headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt");          return ResponseEntity             .ok()             .headers(headers)             .contentLength(resource.contentLength())             .contentType(MediaType.APPLICATION_OCTET_STREAM)             .body(resource); } 
  1. 使用 HttpServletResponse 输出文件流:
@GetMapping("/downloadFile") public void downloadFile(HttpServletResponse response) {     File file = new File("path/to/file.txt");          response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());     response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt");     response.setContentLength((int) file.length());          try (         InputStream inputStream = new FileInputStream(file);         OutputStream outputStream = response.getOutputStream();     ) {         IOUtils.copy(inputStream, outputStream);         outputStream.flush();     } catch (IOException e) {         e.printStackTrace();     } } 

这两种方法都可以实现文件下载,第一种方法使用 ResponseEntity 返回文件资源,第二种方法直接使用 HttpServletResponse 输出文件流。您可以根据自己的需求选择其中一种方法来实现文件下载。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!