我正在尝试使用 ktor 创建一个多部分请求,其代码如下,
import com.firstapp.modal.response.SuccessResponse
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.http.content.PartData
import io.ktor.http.content.forEachPart
import io.ktor.http.content.streamProvider
import io.ktor.locations.Location
import io.ktor.locations.post
import io.ktor.request.isMultipart
import io.ktor.request.receive
import io.ktor.request.receiveMultipart
import io.ktor.response.respond
import io.ktor.routing.Route
import io.ktor.util.getOrFail
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.lang.IllegalArgumentException
@Location("/uploadVideo/{title}")
class UploadVideo(val title:String)
fun Route.upload(uploadDir: File) {
post<UploadVideo> {
val multipart = call.receiveMultipart()
var videoFile: File? = null
// Processes each part of the multipart input content of the user
multipart.forEachPart { part ->
when (part) {
is PartData.FormItem -> {
if (part.name != "title")
throw IllegalArgumentException("Title parameter not found")
//title = part.value
}
is PartData.FileItem -> {
if (part.name != "file")
throw IllegalArgumentException("file parameter not found")
val ext = File(part.originalFileName).extension
val file = File(uploadDir, "upload-${System.currentTimeMillis()}-${call.parameters.getOrFail("title").hashCode()}.$ext")
part.streamProvider().use { input -> file.outputStream().buffered().use { output -> input.copyToSuspend(output) } }
videoFile = file
}
}
part.dispose()
}
call.respond(
HttpStatusCode.OK,
SuccessResponse(
videoFile!!,
HttpStatusCode.OK.value,
"video file stored"
)
)
}
}
suspend fun InputStream.copyToSuspend(
out: OutputStream,
bufferSize: Int = DEFAULT_BUFFER_SIZE,
yieldSize: Int = 4 * 1024 * 1024,
dispatcher: CoroutineDispatcher = Dispatchers.IO
): Long {
return withContext(dispatcher) {
val buffer = ByteArray(bufferSize)
var bytesCopied = 0L
var bytesAfterYield = 0L
while (true) {
val bytes = read(buffer).takeIf { it >= 0 } ?: break
out.write(buffer, 0, bytes)
if (bytesAfterYield >= yieldSize) {
yield()
bytesAfterYield %= yieldSize
}
bytesCopied += bytes
bytesAfterYield += bytes
}
return@withContext bytesCopied
}
}
上面的代码或rest api工作正常,但问题是,我想检查所有参数是否可用,即我想发送附加参数以及格式如下的文件,
class VideoDetail(val type: String, val userId: String, val userName: String)
我在这里举一个例子,我想要什么
post("/") { request ->
val requestParamenter = call.receive<UserInsert>()
}
在这里,无论参数是什么,我们传递的都会自动转换成 pojo 类,如果我们没有传递它,它会抛出异常,
所以,我想用多部分实现类似的事情。