首页 > 其他分享 >feign-reactive 框架下实现图片上传

feign-reactive 框架下实现图片上传

时间:2022-12-08 00:55:16浏览次数:68  
标签:map feign Mono flatMap reactive part key 上传 FilePart

spring webFlux 微服务实现图片上传,经过两天的摸索,我的实现方案是:

  • 首先,把文件一传到消费者,生成FilePart对象,把FilePart对象通过Feign reactive 传给服务者

  • 最后,在服务端读取FilePart对象,再进行保存。

代码如下:

  • 消费端 handler

public Mono<ServerResponse> uploadAvatar(ServerRequest request){
        Mono<MultiValueMap<String, Part>> partMap = request.multipartData();
        return partMap.flatMapIterable(map -> map.keySet().stream()
                        .filter(key -> key.equals("avatar"))
                        .flatMap(key -> map.get(key).stream().filter(part -> part instanceof FilePart))
                        .collect(Collectors.toList()))
                .next()
                .cast(FilePart.class)
                .flatMap(part -> feignService.setAvatar(part)
                        .flatMap(data -> ServerResponse.ok().bodyValue(data))
                        );
    }
  • 消费端 Feign

 @PostMapping(value = "/upload/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Mono <String> setAvatar(@RequestPart("avatar") FilePart files);
  • 服务端

 public Mono<ServerResponse> uploadAvatar(ServerRequest request){
        Mono<MultiValueMap<String, Part>> partMap = request.multipartData();
        System.out.println(partMap);
        return partMap.flatMapIterable(map -> map.keySet().stream()
                        .filter(key -> key.equals("avatar"))
                        .flatMap(key -> map.get(key).stream().filter(part -> part instanceof FilePart))
                        .collect(Collectors.toList()))
                .next()
                .cast(FilePart.class)
                .flatMap(part -> createTempFile()
                        .flatMap(tempFile ->
                                part.transferTo(tempFile).then(ServerResponse.ok().bodyValue(tempFile.toString().substring(29).replaceAll("\\\\","/")))
                        ));
    }

    private Mono<Path> createTempFile() {
        String dir = "/home/fengyun/medical/static/images/avatar";
        String prefix = "bbb" +"_";
        return Mono.defer(() -> {
            try {
                if(Files.notExists(Path.of(dir))){
                    Files.createDirectories(Path.of(dir));
                }
                return Mono.just(Files.createTempFile(Path.of(dir),prefix, ".jpg"));
            }
            catch (IOException ex) {
                return Mono.error(ex);
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }


来自为知笔记(Wiz)

标签:map,feign,Mono,flatMap,reactive,part,key,上传,FilePart
From: https://www.cnblogs.com/baiyifengyun/p/16965016.html

相关文章