More info: http://blog.greweb.fr/?p=1993
Created
November 12, 2012 11:10
-
-
Save gre/4058734 to your computer and use it in GitHub Desktop.
Generate Zip on-the-fly with Play!> Framework (2.1+)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.")) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Link to the blog post is dead. Use this instead: http://greweb.me/2012/11/play-framework-enumerator-outputstream/