Hoang Ong Hoang Ong - 8 months ago 56
Scala Question

How to read file to array bytes from gridfs?

I want to get Array/List[Byte] from Enumerator[Array[Byte]]. Some articles show me how to do it in playframework. But I'm not using play framework for this project. This is what I have:

lazy val gridfs = GridFS[BSONSerializationPack.type](db, "resource")
gridfs.find(BSONDocument("_id" -> BSONObjectID(id))).headOption.map{
case Some(file) => {
//this gives me Enumerator[Array[Byte]].
//I'm not using playframework, how to get Future[Array[Byte]] from here?


Using Play Iteratees is not specific to Play app, but to streaming, like Akka Stream or RxStuff.

You can consume all the chunks of such enumerator using Iteratee.consume.

val sink: Iteratee[Array[Byte], Array[Byte]] = Iteratee.consume[Array[Byte]]()
val allInMem: Future[Array[Byte]] = enumerator |>>> sink

For obvious reason, it's recommanded not to consume big data, but to use appropriate Iteratee to process the data in a streaming way.