Yogeshvu
04/27/2023, 7:54 PMsuspend fun downloadFile(
dir: String
) {
val finalCookie = getCookie()
try {
var fileName = ""
val dirPath = Paths.get(dir)
if (!Files.exists(dirPath)) {
Files.createDirectories(dirPath)
}
val response = webClient.
get()
.uri { uriBuilder: UriBuilder ->
UriComponentsBuilder.fromUri(uriBuilder.build())
.path("/download/file")
.encode()
.build(false)
.toUri()
}
.header(HttpHeaders.COOKIE, finalCookie)
.retrieve()
.onStatus(HttpStatus::is2xxSuccessful) { clientResponse ->
clientResponse.headers().asHttpHeaders().contentDisposition.filename?.let {
fileName = it
}
Mono.empty()
}
.bodyToFlux(DataBuffer::class.java)
when(fileName)
{
"" -> fileName = UUID.randomUUID().toString()
}
val destination = Paths.get(dir, filename)
// Need to use Databuffer so that no memory is used
DataBufferUtils.write(response, destination).block()
println("Downloaded $destination")
} catch (e: Exception) {
println("Error in downloading file: $e")
}
}