简体   繁体   English

如何使用 spring webflux 上传和读取文本文件?

[英]How can i upload and read a text file with spring webflux?

I need to upload a file and read the content, with spring mvc that is easy, but with spring webflux I have no idea how to deal with a FilePart and a Flux of DataBuffer我需要上传文件并阅读内容,使用 spring mvc 这很容易,但是使用 spring webflux 我不知道如何处理 FilePart 和 DataBuffer 的通量

I'm expecting something like this return:我期待这样的回报:

    @PostMapping("/upload")
    fun readFile(@RequestPart("file", required = true) file: Mono<FilePart>): Mono<ResponseEntity<String>> {
        return Mono.just("my text content")
                .map {
                    ResponseEntity.ok()
                            .body(it)
                }
    }

I made it work using the following code:我使用以下代码使其工作:

    @PostMapping("/upload")
fun readFile(@RequestPart("file", required = true) file: Mono<FilePart>): Mono<ResponseEntity<String>> {

    return file.flatMap {
        it.content().map { dataBuffer ->
            IOUtils.inputStreamAsString(dataBuffer.asInputStream(), "UTF-8")
        }.toMono()
    }.map {
        ResponseEntity.ok()
                .body(it)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM