Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felix-schwarz/8385098 to your computer and use it in GitHub Desktop.
Save felix-schwarz/8385098 to your computer and use it in GitHub Desktop.
public class ByteRangeRequestsController extends Controller {
// 206 Partial content Byte range requests
private static Result stream(long start, long length, File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
fis.skip(start);
response().setContentType(MimeTypes.forExtension("mp4").get());
response().setHeader(ACCEPT_RANGES, "bytes");
response().setHeader(CONNECTION, "keep-alive");
// Return partial content with 206 status code and Content-Range header
if ((start!=0) || (length!=(file.length()-1)))
{
response().setHeader(CONTENT_RANGE, String.format("bytes %d-%d/%d", start, length,file.length()));
return status(PARTIAL_CONTENT, fis);
}
// Return requests for complete content with 200 status code and Content-Length header
response().setHeader(CONTENT_LENGTH, file.length()+"");
return (ok(file));
}
// GET a file item
public static Result file(Long id, String filename) throws IOException {
Item item = Item.fetch(id);
File file = item.getFile();
if(file== null || !file.exists()) {
Logger.error("File no longer exist item"+id+" filename:"+filename);
return notFound();
}
String rangeheader = request().getHeader(RANGE);
if(rangeheader != null) {
String[] split = rangeheader.substring("bytes=".length()).split("-");
if(Logger.isDebugEnabled()) { Logger.debug("Range header is:"+rangeheader); }
if(split.length == 1) {
long start = Long.parseLong(split[0]);
long length = file.length()-1l;
return stream(start, length, file);
} else {
long start = Long.parseLong(split[0]);
long length = Long.parseLong(split[1]);
return stream(start, length, file);
}
}
// if no streaming is required we simply return the file as a 200 OK
if(Play.isProd()) {
response().setHeader("Cache-Control", "max-age=3600, must-revalidate");
}
return ok(file);
}
}
@zarinfam
Copy link

Thank you very much, this is very useful for us.

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