如何使用 Ktor 客户端上传文件

How to upload a file using Ktor client

我看过the docs关于Ktor客户端的HTTP请求,但是缺少文件上传的例子。它提到了PartData.FileItem,但不清楚如何使用它。

那么,如何在 Ktor 中准备 multipart/form-data 文件上传请求?

您应该使用 submitFormWithBinaryData's formData parameter to provide a list of parts. There is a helper function with the same name 创建这样的列表。

HttpClient(Apache).use { client ->
    val parts: List<PartData> = formData {
        // Regular form parameter
        append("text", "Hello, world")

        // File upload. Param name is "file-1" and file's name is "file.csv"
        append("file-1", "file.csv", ContentType.Text.CSV) {
            this.append("1,2,3")
        }

        // Verbose DSL
        val headersBuilder = HeadersBuilder()
        headersBuilder[HttpHeaders.ContentType] = "application/java-archive"
        headersBuilder[HttpHeaders.ContentDisposition] = "filename=wrapper.jar"
        this.append(
                "file-2",
                InputProvider { File("gradle/wrapper/gradle-wrapper.jar").inputStream().asInput() },
                headersBuilder.build()
        )
    }

    client.submitFormWithBinaryData<Unit>(formData = parts /* prepared parts */) {
        url("https://hookb.in/XXX")

        // Query string parameters
        parameter("param-1", "value-1")
        parameter("param-2", "value-2-1")
        parameter("param-2", "value-2-2")

        // Headers
        headers {
            this["X-My-Header-1"] = "X-My-Header-1-Value"
            appendAll("X-My-Header-2", listOf("X-My-Header-2-Value-1", "X-My-Header-2-Value-2"))
        }
    }
}