As we all know, Spring cloud gateway is implemented based on webflux reactive programming mode, so how do we upload files to third-party cloud services such as Alibaba Cloud and Tencent Cloud in webflux mode? Taking Alibaba Cloud as an example, we use the Mendmix file upload component to achieve the above requirements.

import dependencies

 <dependency>
  <groupId>com.mendmix</groupId>
  <artifactId>mendmix-cos-adapter</artifactId>
  <version>1.4.0</version>
</dependency>

<dependency>
  <groupId>com.aliyun.oss</groupId>
  <artifactId>aliyun-sdk-oss</artifactId>
  <version>3.11.3</version>
</dependency>

add configuration

 #aliyun OSS
mendmix.cos.adapter.type=aliyun
mendmix.cos.adapter.accessKey=5tHzzxhTs45tbUrKgTHYxxxx
mendmix.cos.adapter.secretKey=aIDWMP2pbvFjML7tYAzfPXXXXXXX
mendmix.cos.adapter.regionName=cn-guangzhou

Then paste the code

 @RestController
@RequestMapping(GatewayConstants.PATH_PREFIX)
public class CommonController {

    @Autowired(required = false)
    private CosProvider cosProvider;
    
    @PostMapping("file/upload")
    @ResponseBody
    @ApiMetadata(actionName = "上传文件",permissionLevel = PermissionLevel.LoginRequired,requestLog = false)
    public Mono<WrapperResponse<CUploadResult>> upload(ServerHttpRequest request,@RequestPart("file") FilePart filePart) {
        
        Flux<DataBuffer> bufferFlux = filePart.content();
        Mono<WrapperResponse<CUploadResult>> mono;
        mono = bufferFlux.map(dataBuffer -> dataBuffer.asInputStream()) //
                .reduce(SequenceInputStream::new) //
                .flatMap(inputStream -> {
                    try {
                        byte[] bytes = IOUtils.toByteArray(inputStream);
                        CUploadResult result = cosProvider.upload(new CUploadObject(bytes, null));
                        return Mono.just(new WrapperResponse<>(result));
                    } catch (IOException e) {
                        e.printStackTrace();
                        return Mono.just(new WrapperResponse<>(500,"上传失败"));
                    }
                });
        return mono;
    }
}

This is done.

Mendmix is positioned as a one-stop distributed development architecture open source solution and cloud native architecture technology base. Mendmix provides database, cache, message middleware, distributed timing tasks, security framework, gateway and rapid integration capabilities of mainstream manufacturers' cloud services. Based on Mendmix, you can quickly build a distributed architecture based on microservices with high concurrency and high availability without paying attention to technical details.

在路上
4 声望7 粉丝

开源拥趸,5年企业级开源技术推广,6年个人开源项目持续投入。对微服务、k8s、DDD、中台建设有一定见解。欢迎交流。