我今天搜索了很多,但所有的答案似乎只在nodejs中。我目前正在开发ktor应用程序,我似乎找不到任何方法将图像上传到MongoDB和KMongo中。
发布于 2021-09-13 12:31:32
您可以使用GridFS在MongoDB中存储和检索二进制文件。下面是在multipart/form-data数据库中存储用test方法请求的图像的示例:
import com.mongodb.client.gridfs.GridFSBuckets
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.litote.kmongo.KMongo
fun main() {
val client = KMongo.createClient()
val database = client.getDatabase("test")
val bucket = GridFSBuckets.create(database, "fs_file")
embeddedServer(Netty, port = 8080) {
routing {
post("/image") {
val multipartData = call.receiveMultipart()
multipartData.forEachPart { part ->
if (part is PartData.FileItem) {
val fileName = part.originalFileName as String
withContext(Dispatchers.IO) {
bucket.uploadFromStream(fileName, part.streamProvider())
}
call.respond(HttpStatusCode.OK)
}
}
}
}
}.start()
}若要发出请求,请运行以下curl命令:curl -v -F image.jpg=@/path/to/image.jpg http://localhost:8080/image
若要检查存储的文件,请在mongo中运行db.fs_file.files.find()。
https://stackoverflow.com/questions/69151731
复制相似问题