Last active
May 3, 2020 16:28
-
-
Save samuelorji/e108f5f5a65b62f1329a1ef87f2baf98 to your computer and use it in GitHub Desktop.
Streaming
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
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