Skip to content

Latest commit

 

History

History

reactive-multiple

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

使用 Spring WebFlux REST 接口上传文件

WebFlux 构建的文件上传应用,使用REST 接口

添加依赖 build.gradle

dependencies {
    implementation('org.springframework.boot:spring-boot-starter-webflux')
    implementation('org.projectlombok:lombok')

    testImplementation('org.springframework.boot:spring-boot-starter-test')
    testImplementation('io.projectreactor:reactor-test')
}

添加接口

  • REST 接口
@RestController
@RequestMapping("/upload")
@Slf4j
public class MultipleController {

    @PostMapping(value = "", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Flux<String> upload(@RequestBody Flux<Part> parts) {
        return parts
                .filter(part -> part instanceof FilePart)
                .ofType(FilePart.class)
                .flatMap(filePart -> filePart.transferTo(new File(filePart.filename()))
                        .log()
                        .thenReturn(filePart.filename() + " Upload success"));
    }

}
  • 添加上传页面

index.html

<form enctype="multipart/form-data" action="/upload" method="post">
    <input type="file" name="uploadFile">
    <br>
    <button type="submit">Submit</button>
</form>

添加配置

  • CustomWebFilter.java 访问时跳转到首页
@Component
public class CustomWebFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        if ("/".equals(exchange.getRequest().getURI().getPath())) {
            return chain.filter(
                    exchange.mutate()
                            .request(
                                    exchange.getRequest()
                                            .mutate()
                                            .path("/index.html")
                                            .build()
                            )
                            .build()
            );
        }
        return chain.filter(exchange);
    }
}

测试