Skip to content

Instantly share code, notes, and snippets.

@dvas0004 dvas0004/DefaultRouter.kt
Last active Jul 9, 2018

Embed
What would you like to do?
A clear, simple example of multipart file upload using Reactive Spring (http://blog.davidvassallo.me/2018/07/09/reactive-spring-webflux-multipart-file-upload/)
package com.example.FileUploadExample
import com.example.FileUploadExample.HomeHandler
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.server.HandlerFunction
import org.springframework.web.reactive.function.server.RequestPredicates
import org.springframework.web.reactive.function.server.RouterFunction
import org.springframework.web.reactive.function.server.RouterFunctions
import org.springframework.web.reactive.function.server.ServerResponse
@Configuration
class DefaultRouter{
@Bean
fun route(homeHandler: HomeHandler): RouterFunction<ServerResponse> {
return RouterFunctions
.route(RequestPredicates.POST("/upload/{id}").and(RequestPredicates.accept(MediaType.MULTIPART_FORM_DATA)),
HandlerFunction<ServerResponse> { homeHandler.upload(it) })
}
}
package com.example.FileUploadExample
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class FileUploadExample
fun main(args: Array<String>) {
runApplication<FileUploadExample>(*args)
}
package com.example.FileUploadExample
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.codec.multipart.FilePart
import org.springframework.http.codec.multipart.Part
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyExtractors
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.bodyToServerSentEvents
import reactor.core.publisher.Mono
import java.io.File
@Component
class HomeHandler {
fun upload(request: ServerRequest): Mono<ServerResponse> {
// Not used in this example, but useful for logging, etc
val id = request.pathVariable("id")
return request.body(BodyExtractors.toMultipartData()).flatMap { parts ->
val map: Map<String, Part> = parts.toSingleValueMap()
val filePart : FilePart = map["file"]!! as FilePart
// Note cast to "FilePart" above
// Save file to disk - in this example, in the "tmp" folder of a *nix system
val fileName = filePart.filename()
filePart.transferTo( File("/tmp/$fileName"))
ServerResponse.ok().body(BodyInserters.fromObject("OK"))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.