hey, I am writing a function about upload file wit...
# coroutines
k
hey, I am writing a function about upload file with spring-webflux and kotlin coroutines, and this is my code
Copy code
@PostMapping("/upload", consumes = ["multipart/form-data"])
    suspend fun uploadFile(@RequestPart("file") file: Mono<FilePart>,
                           @RequestPart("path") path: String): Mono<Void> = coroutineScope {

        val filepart = file.awaitSingle()
        val tempfile = File("/tmp/tempfile")
        val outputStream = tempfile.outputStream()

        DataBufferUtils.write(filepart.content(), outputStream).then()
    }
but I want to launch a coroutine to write this code, how can I do it ? I don't want Mono
h
Don’t use
suspend
and
Mono
and just „return“
Unit
. You can also use Flow<FilePart>.
r
Simple
@RequestPart("file") file: FilePart
is enough.
k
ok, I change my code into this
Copy code
@PostMapping("/upload", consumes = ["multipart/form-data"])
    suspend fun uploadFile(@RequestPart("file") filepart: FilePart,
                           @RequestPart("path") path: String): Response.Ok<Unit> = coroutineScope {



            Response.Ok("Ok", Unit)
    }
now how can I write the code, sorry I am not very familiar with nio and webflux
h
There is no flux/reactor api anymore, but Kotlinx coroutines. So just use normal Kotlin code.
k
like this ?
Copy code
@PostMapping("/upload", consumes = ["multipart/form-data"])
    suspend fun uploadFile(@RequestPart("file") filepart: FilePart,
                           @RequestPart("path") path: String): Response.Ok<Unit> = coroutineScope {

        filepart.transferTo(File(path))
        
        Response.Ok("Ok", Unit)
    }
or can you give me an example pls, I don't know how to handle the
FilePart
hey, you say there is no flux/reactor api anymore, but how can I process download file in webflux ?
Copy code
@GetMapping("/download", params = ["path"])
    suspend fun downloadFile(@RequestParam("path") path: String,
                             response: ServerHttpResponse): Mono<Void> {
        val sambafile = sambaUtils.file(path)

        response.headers.contentType = MediaType.APPLICATION_OCTET_STREAM
        response.headers.contentLength = sambafile.length()
        
        
        val databuffer = response.bufferFactory().allocateBuffer(bufferSize)
        val outputStream = databuffer.asOutputStream()
        val inputStream = sambafile.inputStream
        val buffer = ByteArray(bufferSize)

        coroutineScope {
            var n = inputStream.read(buffer)
            while (n != -1) {
                outputStream.write(buffer, 0, n)
                n = inputStream.read(buffer)
            }

            outputStream.flush()
            inputStream.close()
            outputStream.close()
        }

        return response.writeWith(Mono.just(databuffer))

    }
how can I rewrite this code with kotlinx coroutines ?
183 Views