Multipart Support
note
This help topic is in development and will be updated in the future.
Ktor supports handling HTTP Uploads. As well as receiving any other kind of content.
note
You can check out the Youkube example for a full example of this in action.
Receiving files using multipart
1. val multipart = call.receiveMultipart()
2. multipart.forEachPart { part ->
3. when (part) {
4. is PartData.FormItem -> {
5. if (part.name == "title") {
6. title = part.value
7. }
8. }
9. is PartData.FileItem -> {
10. val ext = File(part.originalFileName).extension
11. val file = File(uploadDir, "upload-${System.currentTimeMillis()}-${session.userId.hashCode()}-${title.hashCode()}.$ext")
12. part.streamProvider().use { input -> file.outputStream().buffered().use { output -> input.copyToSuspend(output) } }
13. videoFile = file
14. }
15. }
17. part.dispose()
18. }
20. suspend fun InputStream.copyToSuspend(
21. out: OutputStream,
22. bufferSize: Int = DEFAULT_BUFFER_SIZE,
23. yieldSize: Int = 4 * 1024 * 1024,
24. dispatcher: CoroutineDispatcher = Dispatchers.IO
25. ): Long {
26. return withContext(dispatcher) {
27. val buffer = ByteArray(bufferSize)
28. var bytesCopied = 0L
29. var bytesAfterYield = 0L
30. while (true) {
31. val bytes = read(buffer).takeIf { it >= 0 } ?: break
32. out.write(buffer, 0, bytes)
33. if (bytesAfterYield >= yieldSize) {
34. yield()
35. bytesAfterYield %= yieldSize
36. }
37. bytesCopied += bytes
38. bytesAfterYield += bytes
39. }
40. return@withContext bytesCopied
41. }
42. }

