springboot下载文件的方法是什么

   2024-11-05 2870
核心提示:在Spring Boot中,您可以使用以下方法来下载文件:使用ResponseEntitybyte[]返回文件数据和相关的HTTP头信息。@GetMapping(/down

在Spring Boot中,您可以使用以下方法来下载文件:

使用ResponseEntity<byte[]>返回文件数据和相关的HTTP头信息。
@GetMapping("/download")public ResponseEntity<byte[]> downloadFile() throws IOException {    // 从文件系统或其他来源获取文件    File file = new File("path/to/file");    // 将文件读入字节数组    byte[] fileContent = Files.readAllBytes(file.toPath());    // 设置HTTP头信息    HttpHeaders headers = new HttpHeaders();    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    headers.setContentDispositionFormData("attachment", file.getName());    // 返回ResponseEntity对象    return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);}
使用InputStreamResourceResponseEntity<InputStreamResource>返回文件的输入流和相关的HTTP头信息。
@GetMapping("/download")public ResponseEntity<InputStreamResource> downloadFile() throws IOException {    // 从文件系统或其他来源获取文件    File file = new File("path/to/file");    // 创建文件输入流    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));    // 设置HTTP头信息    HttpHeaders headers = new HttpHeaders();    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    headers.setContentDispositionFormData("attachment", file.getName());    // 返回ResponseEntity对象    return ResponseEntity.ok()            .headers(headers)            .contentLength(file.length())            .body(resource);}

这两种方法都可以用来下载文件,具体使用哪种方法取决于您的需求和偏好。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号