Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Created June 22, 2012 16:29
Show Gist options
  • Select an option

  • Save masahitojp/2973860 to your computer and use it in GitHub Desktop.

Select an option

Save masahitojp/2973860 to your computer and use it in GitHub Desktop.
serveletからoctet-streamでファイルダウンロードするサンプルコード。
package com.github.masahitojp
import org.scalatra._
import java.io.File
class BaseServlet extends ScalatraServlet {
// ***************************************
// GLOBAL METHODS
before() {
println("Before " + this.getClass)
}
after() {
println("After " + this.getClass)
}
notFound {
<html>
<body>
<h1>Ooops</h1>
I'm terribly sorry, but we have a 404 not found problem here!
{this.getClass}
</body>
</html>
}
get("/file"){
val file = new File("/home/test/a.tar.gz")
com.skeedtech.deliver.Test.printOutFile(request,response,file)
}
}
package com.github.masahitojp
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
object Test {
def printOutFile(req: HttpServletRequest , res: HttpServletResponse, fileOut: File) {
var os = res.getOutputStream
try {
val hFile:FileInputStream = new FileInputStream(fileOut)
val bis: BufferedInputStream = new BufferedInputStream(hFile)
res.setContentType("application/octet-stream")
res.setHeader("Content-Disposition", "filename=\"" + fileOut.getName + "\"")
var len: Int = 0
val buffer: Array[Byte] = new Array[Byte](1024*1024)
while ((({
len = bis.read(buffer); len
})) >= 0) {
os.write(buffer, 0, len)
}
bis.close
}
catch {
case e: IOException => {
printOutNotFound(res)
}
}
finally {
if (os != null) {
try {
os.close
}
catch {
case e: IOException => {
}
}
finally {
os = null
}
}
}
}
private def printOutNotFound(res: HttpServletResponse) {
try {
val toClient = res.getOutputStream
res.setContentType("text/html;charset=utf-8")
toClient.write("File not found".getBytes)
toClient.close
}
catch {
case e: IOException => {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment