Search code examples
mongodbktorkmongo

How do I save an image into a mongoDB collection using Kmongo?


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.


Solution

  • 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.