Skip to content

Instantly share code, notes, and snippets.

@sreevatsanraman
Created December 2, 2015 06:05
Show Gist options
  • Save sreevatsanraman/9d2b9de0364770b03848 to your computer and use it in GitHub Desktop.
Save sreevatsanraman/9d2b9de0364770b03848 to your computer and use it in GitHub Desktop.
Streaming use-case using netty-http
// BodyConsumer abstract-class is used to handle large files,
// we can handle the chunks as we receive it
// and handle clean up when we are done in the finished methodi
@Path("/upload")
@PUT
public BodyConsumer streamUploadFile(HttpRequest request, HttpResponder responder) throws FileNotFoundException {
final File file = new File(request.getHeader("File-Path"));
final FileChannel fileChannel = new FileOutputStream(file).getChannel();
return new BodyConsumer() {
@Override
public void chunk(ChannelBuffer request, HttpResponder responder) {
try {
// write the incoming chunks
fileChannel.write(request.toByteBuffer());
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public void finished(HttpResponder responder) {
try {
fileChannel.close();
// Upload is finished. Respond with success.
responder.sendStatus(HttpResponseStatus.OK);
} catch (IOException e) {
// handle exception
}
}
@Override
public void handleError(Throwable cause) {
Closeables.closeQuietly(fileChannel);
// delete the file since the upload failed on error.
file.delete();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment