首页 > 解决方案 > 如何使用 Kmongo 将图像保存到 mongoDB 集合中?

问题描述

我今天搜索了很多,但所有答案似乎都只在 nodejs 中。我目前正在开发 ktor 应用程序,我似乎找不到任何方法可以使用 KMongo 将图像上传到 MongoDB。

标签: mongodbktorkmongo

解决方案


您可以使用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

db.fs_file.files.find()检查在 mongo shell 中运行的存储文件。


推荐阅读