又要开一个接收文件上传的服务,找了官方的样例代码,把不需要的东西删了一圈,很容易就实现了。
Bootstrap没什么变化,所以只写上initChannel需要加载的处理器
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
// TODO Auto-generated method stub
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpRequestDecoder());
pipeline.addLast(new HttpResponseEncoder());
pipeline.addLast("compressor", new HttpContentCompressor());
pipeline.addLast(new HttpFileHandler());
}
});
然后是HttpFileHandler.java这个超级大的处理器,把import也贴出来了,因为像Cookie类的位置有了变化,可能需要在import里面确认一下来消除warning。
这个处理器的原理是接收HttpObject对象,按照HttpRequest,HttpContent来做处理,文件内容是在HttpContent消息带来的。
在这个样例中,只响应feed的Post请求,其他的请求都被
if (!path.startsWith("/feed") ||request.getMethod().equals(HttpMethod.GET))
滤掉了- 针对HttpRequest只做了两件事,构造一个解码器decoder,看请求中是否含multi-part。
- 初始化静态代码块设置文件下载的特性
static {
DiskFileUpload.deleteOnExitTemporaryFile =true; // should delete file
// on exit (in normal
// exit)
&