Spring WebFlux:从控制器提供文件

Spring WebFlux:从控制器提供文件,第1张

Spring WebFlux:从控制器提供文件

首先,使用Spring MVC实现该目标的方法应如下所示:

@RestController@RequestMapping("/files")public class FileController {    @GetMapping("/{fileName}")    public Resource getFile(@PathVariable String fileName) {        Resource resource = new FileSystemResource(fileName);     return resource;    }}

另外,如果您 在没有其他逻辑的情况下 托管这些资源,则可以使用Spring
MVC的静态资源支持。使用Spring
Boot,

spring.resources.static-locations
可以帮助您自定义位置。

现在,使用Spring WebFlux,您还可以配置相同的

spring.resources.static-locations
配置属性来提供静态资源。

它的WebFlux版本看起来完全一样。如果您需要执行涉及某些I / O的逻辑,则可以返回a

Mono<Resource>
而不是
Resource
直接返回a ,如下所示:

@RestController@RequestMapping("/files")public class FileController {    @GetMapping("/{fileName}")    public Mono<Resource> getFile(@PathVariable String fileName) {        return fileRepository.findByName(fileName)      .map(name -> new FileSystemResource(name));    }}

请注意,使用WebFlux,如果返回

Resource
的实际上是磁盘上的文件,我们将利用零复制机制,这将使事情更高效。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5666458.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存