Skip to content

Instantly share code, notes, and snippets.

@samuelorji
Last active May 3, 2020 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelorji/e108f5f5a65b62f1329a1ef87f2baf98 to your computer and use it in GitHub Desktop.
Save samuelorji/e108f5f5a65b62f1329a1ef87f2baf98 to your computer and use it in GitHub Desktop.
Streaming
val route = path("download") {
get {
optionalHeaderValueByName("Range") {
case None =>
// there must always be range
complete(StatusCodes.RequestedRangeNotSatisfiable)
case Some(range) =>
val file = new File("movie.mp4")
val fileSize = file.length()
val rng = range.split("=")(1).split("-")
val start = rng(0).toInt
val end = if (rng.length > 1) {
//there is end range
rng(1).toLong
} else {
fileSize - 1
}
respondWithHeaders(List(
RawHeader("Content-Range", s"bytes ${start}-${end}/${fileSize}"),
RawHeader("Accept-Ranges", s"bytes")
)) {
complete {
val chunkSize = 1024 * 1000 * 4 // read 4MB of data = 4,096,000 Bytes
val raf = new RandomAccessFile(file, "r")
val dataArray = Array.ofDim[Byte](chunkSize)
raf.seek(start) // start readinng from `start` position
val bytesRead = raf.read(dataArray, 0, chunkSize)
val readChunk = dataArray.take(bytesRead)
HttpResponse(StatusCodes.PartialContent,
entity = HttpEntity(MediaTypes.`video/mp4`, readChunk))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment