I searched a lot today but all answers seem to be only in nodejs. I'm currently working on ktor application and I can't seem to find any way to upload images into MongoDB with KMongo.
Asked
Active
Viewed 698 times
1 Answers
2
You can use GridFS to store and retrieve binary files in MongoDB. Here is an example of storing an image, that is requested with the multipart/form-data
method, in a test
database:
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()
}
To make a request run the following curl command: curl -v -F image.jpg=@/path/to/image.jpg http://localhost:8080/image
To inspect stored files run db.fs_file.files.find()
in the mongo shell.

Aleksei Tirman
- 4,658
- 1
- 5
- 24
-
I'm trying to implement the exact same thing as your code shows in order to get the point of uploading an image file, but the problem is that the IDE does not resolve the function called uploadFromStream. Is that a custom function you have in your code or should I use uploadFromPublisher instead? – Astro Sep 14 '21 at 14:25
-
I found out that it is a function in GridFSBucket Interface. However, maybe it's something with the driver version of mongoDB? – Astro Sep 14 '21 at 14:55
-
-
I use the `org.litote.kmongo:kmongo:4.3.0` dependency in Gradle.`uploadFromStream` is not my function but one from the `com.mongodb.client.gridfs` package. – Aleksei Tirman Sep 15 '21 at 08:04