Skip to content

Instantly share code, notes, and snippets.

@gre
Created November 12, 2012 11:10
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save gre/4058734 to your computer and use it in GitHub Desktop.
Save gre/4058734 to your computer and use it in GitHub Desktop.
Generate Zip on-the-fly with Play!> Framework (2.1+)
package controllers
import play.api._
import play.api.mvc._
object Application extends Controller {
def zip = Action {
import play.api.libs.iteratee._
import java.util.zip._
val r = new java.util.Random()
val enumerator = Enumerator.outputStream { os =>
val zip = new ZipOutputStream(os);
Range(0, 100).map { i =>
zip.putNextEntry(new ZipEntry("test-zip/README-"+i+".txt"))
zip.write("Here are 100000 random numbers:\n".map(_.toByte).toArray)
// Let's do 100 writes of 1'000 numbers
Range(0, 100).map { j =>
zip.write((Range(0, 1000).map(_=>r.nextLong).map(_.toString).mkString("\n")).map(_.toByte).toArray);
}
zip.closeEntry()
}
zip.close()
}
Ok.stream(enumerator >>> Enumerator.eof).withHeaders(
"Content-Type"->"application/zip",
"Content-Disposition"->"attachment; filename=test.zip"
)
}
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
}
/** Create an Enumerator of bytes with an OutputStream.
*/
def outputStream(a: java.io.OutputStream => Unit): Enumerator[Array[Byte]] = {
Concurrent.unicast[Array[Byte]] { channel =>
val outputStream = new java.io.OutputStream(){
override def close() {
channel.end()
}
override def flush() {}
override def write(value: Int) {
channel.push(Array(value.toByte))
}
override def write(buffer: Array[Byte]) {
write(buffer, 0, buffer.length)
}
override def write(buffer: Array[Byte], start: Int, count: Int) {
channel.push(buffer.slice(start, start+count))
}
}
a(outputStream)
}
}
@brock
Copy link

brock commented Sep 18, 2015

Link to the blog post is dead. Use this instead: http://greweb.me/2012/11/play-framework-enumerator-outputstream/

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