mongodb - 如何使用 Kmongo 将图像保存到 mongoDB 集合中?
问题描述
我今天搜索了很多,但所有答案似乎都只在 nodejs 中。我目前正在开发 ktor 应用程序,我似乎找不到任何方法可以使用 KMongo 将图像上传到 MongoDB。
解决方案
您可以使用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 中运行的存储文件。
推荐阅读
- windows - 如何锁定 docker 的 config.json 文件?
- r - 从模拟数据中分离两个类
- javascript - 如何从 `.txt` 或 `.css` 文件中获取 html 中选项标签中的数据?
- javascript - JS 跳过第一个事件的 if 语句
- dependencies - .deb 取决于间隔
- python - 如何规范化非均匀 Python 数据帧
- php - 在 Laravel 中获取 allDirectories() 并创建一棵树
- python - 获取其他列中唯一值的最大值行:python
- node.js - 为 2FA 实施生成恢复代码
- assembly - AT&T asm ascii 整数转换