意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

在SpringBoot中,您可以使用以下方法来下载文件

来源:恒创科技 编辑:恒创科技编辑部
2024-02-04 13:53:42

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

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

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


    

在SpringBoot中,您可以使用以下方法来下载文件

    上一篇: xshell怎么连接云服务器? 下一篇: 要查看所有数据库,可以使用以下命令