Reputation: 687
Hey So I have the following code that is used by a client side application to play a video file that is stored in MongoDB(using GridFS).
My question here is does the code have to wait until every byte that makes up the video file is written into the stream, before sending the response back to the client?
Obviously if that was the case it would be highly undesirable as this consumes all bytes into memory, which means large files could bring down the server. The purpose of streaming is to avoid consuming all bytes into memory.
@Path("video/{videoId}")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getTheSelectedVideo(@PathParam("videoId") String videoId){
GridFSDBFile videoFile = gridFS.findOne(new ObjectId(videoId));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
return Response.ok(videoFile.writeTo(baos)).build();
}
catch (IOException e) {
e.printStackTrace();
return Response.serverError().build();
}
}
Note gridFS here refers to a GridFS object created further up in the code.
Any help on clearing this up would be great! Thanks.
Upvotes: 0
Views: 795
Reputation: 209082
You can use StreamingOutput
to stream the output. For example
@Path("video/{videoId}")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getTheSelectedVideo(@PathParam("videoId") String videoId){
final GridFSDBFile videoFile = gridFS.findOne(new ObjectId(videoId));
StreamingOutput entity = new StreamingOutput() {
@Override
public void write(OutputStream output)
throws IOException, WebApplicationException {
InputStream in = videoFile.getInputStream();
ReaderWriter.writeTo(in, output);
}
};
return Response.ok(entity).build();
}
ReaderWriter
is just an OP helper. But what StreamingOutput
does is allow you to write straight to the response output stream. There is a default buffer size of 8192 bytes. If you want to change this to something lower, you can set this property, but this affects the entire application. Make sure to read the javadoc to get all the details, if this is something you wan to do.
Upvotes: 0