Forked from stopher/ByteRangeRequestsController.java
Last active
January 3, 2016 00:49
-
-
Save felix-schwarz/8385098 to your computer and use it in GitHub Desktop.
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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much, this is very useful for us.