在SpringBoot中,您可以使用以下方法来下载文件
在SpringBoot中,您可以使用以下方法来下载文件:
- 使用
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);
}
InputStreamResource
和ResponseEntity<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);
}
这两种方法都可以用来下载文件,具体使用哪种方法取决于您的需求和偏好。
版权声明
本文仅代表作者观点,不代表博信信息网立场。