Alex Styl
03/22/2024, 7:45 AMAleksei Tirman [JB]
03/22/2024, 8:56 AMAlex Styl
03/22/2024, 9:06 AMAlex Styl
03/22/2024, 9:07 AMhttpClient.submitFormWithBinaryData(POST_URL,
formData = formData {
val byteArray = source
.use {
it.buffer()
.use { bufferFileSource ->
bufferFileSource.readByteArray()
}
}
append("file", byteArray, Headers.build {
append(
HttpHeaders.ContentType,
ContentType.Image.Any
)
append(
HttpHeaders.ContentDisposition,
"filename=\"$fileName\""
)
}
)
}
)
I am concerned about this because it reads the file in one go and I want to support really big filesAlex Styl
03/22/2024, 9:09 AMSource
to 'something' (not sure about the API yet) that can upload the file without reading it in one go, to avoid OOM errorsAleksei Tirman [JB]
03/22/2024, 11:34 AMSource
to InputStream
and then to Input
. Here is an example:
val source = FileSystem.SYSTEM.source("archive.zip".toPath())
val client = HttpClient(OkHttp)
val response = client.submitFormWithBinaryData("<https://httpbin.org/post>", formData = formData {
append("file", InputProvider(null) { source.buffer().inputStream().asInput() }, Headers.build {
append(HttpHeaders.ContentType, ContentType.Image.Any)
append(HttpHeaders.ContentDisposition, "filename=\"file.bin\"")
})
})
println(response.bodyAsText())
Alex Styl
03/22/2024, 2:39 PM.inputStream()
from? the IDE says it's in the kotlin's stdlib but I added it in the commonMain dependencies and it doesn't pick i tupAleksei Tirman [JB]
03/22/2024, 2:39 PMAlex Styl
03/22/2024, 2:40 PMInputStream
is a java API. that is not available for multiplatformAleksei Tirman [JB]
03/22/2024, 2:41 PMAlex Styl
03/22/2024, 2:44 PM.inputStream()
and .asInput()
works under the hood and will try to do a buffer().asInput()
tomorrow.
If that piece of code already exists somewhere, it would be super helpfulAlex Styl
03/22/2024, 3:25 PMprivate fun BufferedSource.asInput(): Input {
val source = this
return object : Input() {
override fun fill(destination: Memory, offset: Int, length: Int): Int {
val buffer = ByteArrayPool.borrow()
try {
val rc = source.read(buffer, 0, minOf(buffer.size, length))
if (rc == -1) return 0
destination.storeByteArray(offset, buffer, 0, rc)
return rc
} finally {
ByteArrayPool.recycle(buffer)
}
}
override fun closeSource() {
source.close()
}
}
}