Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active September 15, 2017 09:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loicdescotte/8456668 to your computer and use it in GitHub Desktop.
Save loicdescotte/8456668 to your computer and use it in GitHub Desktop.
Stream and transform file with Play

Chunck by chunk

def  transform = Action {
    
     val fileStream: Enumerator[Array[Byte]] = {
         Enumerator.fromFile(new File("data.txt"))
     }
     
     val transfo = Enumeratee.map[Array[Byte]]{byteArray =>  
         val chunckedString = new String(byteArray)
         //add blablabla on each line
         val newChunk = chunckedString.replaceAll("\n", " blablabla\n")         
         //newChunk <-- stream text
         newChunk.getBytes //<-- stream file
     }
               
     Ok.stream(fileStream.through(transfo))            
}

Line by line

def  transform = Action {
    lazy val bufferedReader =  new BufferedReader(new InputStreamReader(new FileInputStream("data.txt")))
     
     val fileStream : Enumerator[String] = Enumerator.generateM[String] {
        scala.concurrent.Future{
          val line: String = bufferedReader.readLine()
          Option(line)  
        }
      }
     
     val transfo = Enumeratee.map[String]{line =>  
         val newLine = line + " blablabla" + "\n"
         newLine.getBytes
     }
               
    Ok.stream(fileStream.through(transfo)) 
}
@karthikeyan-kandasamy
Copy link

karthikeyan-kandasamy commented May 24, 2016

@loicdescotte, Thank you for your code. I need to stream a image from the S3. How do I do this in Play scala framework. I did the following. But it didn't work.

           val objectComplete = s3Service.getObject(bucket, "user/1/profileIcon.jpg");
           val reader = new BufferedReader(
                new InputStreamReader(objectComplete.getDataInputStream()));
            val fileStream : Enumerator[String] = Enumerator.generateM[String] {
                scala.concurrent.Future{
                    val line: String = reader.readLine()
                    Option(line)
                }
            }
            val transfo = Enumeratee.map[String]{line =>
                val newLine = line + " blablabla" + "\n"
                newLine.getBytes
            }

            Ok.chunked(fileStream.through(transfo)).as("image/jpeg");

How do I display the image in "". Can you please help me to fix this issue?
Note: I need to do it for video also.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment