Hoang Ong Hoang Ong - 1 year ago 153
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download