Created
November 26, 2012 19:54
-
-
Save darkfrog26/4150246 to your computer and use it in GitHub Desktop.
This file contains 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
import org.jboss.netty.channel.ChannelHandlerContext; | |
import org.jboss.netty.channel.MessageEvent; | |
import org.jboss.netty.channel.SimpleChannelUpstreamHandler; | |
import org.jboss.netty.handler.codec.http.HttpChunk; | |
import org.jboss.netty.handler.codec.http.HttpRequest; | |
import org.jboss.netty.handler.codec.http.multipart.*; | |
/** | |
* HttpUploadHandler provides an easy-to-use abstract handler for parsing multipart form data on the server. | |
* | |
* This code contains no license and is free for all to use. I would request that credit be given to me for any derived work though. | |
* | |
* @author Matt Hicks <matt@outr.com> | |
*/ | |
public abstract class HttpUploadHandler extends SimpleChannelUpstreamHandler { | |
private final DefaultHttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); | |
private HttpPostRequestDecoder decoder; | |
@Override | |
public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception { | |
if (event.getMessage() instanceof HttpRequest) { | |
HttpRequest request = (HttpRequest)event.getMessage(); | |
decoder = new HttpPostRequestDecoder(factory, request); | |
if (!request.isChunked()) { | |
uploadFinished(context); | |
} | |
} else if (event.getMessage() instanceof HttpChunk) { | |
HttpChunk chunk = (HttpChunk)event.getMessage(); | |
decoder.offer(chunk); | |
if (chunk.isLast()) { | |
uploadFinished(context); | |
} | |
} | |
} | |
private void uploadFinished(ChannelHandlerContext context) throws HttpPostRequestDecoder.NotEnoughDataDecoderException { | |
for (InterfaceHttpData data : decoder.getBodyHttpDatas()) { | |
if (data instanceof Attribute) { | |
receivedAttribute((Attribute)data); | |
} else if (data instanceof FileUpload) { | |
receivedFileUpload((FileUpload)data); | |
} | |
} | |
sendResponse(context); | |
} | |
/** | |
* Invoked when this upload handler receives a form attribute. | |
*/ | |
public abstract void receivedAttribute(Attribute attribute); | |
/** | |
* Invoked when this upload handler receives a file. | |
*/ | |
public abstract void receivedFileUpload(FileUpload upload); | |
/** | |
* Invoked after all upload data is received and a response should be sent back to the client. | |
*/ | |
public abstract void sendResponse(ChannelHandlerContext context); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment