文件上传

这个处理器的原理是接收HttpObject对象,按照HttpRequest,HttpContent来做处理,文件内容是在HttpContent消息带来的。

然后在HttpContent中一个chunk一个chunk读,chunk大小可以在初始化HttpServerCodec时设置。将每个chunk交个httpDecoder复制一份,当读到LastHttpContent对象时,表明上传结束,可以将httpDecoder中缓存的文件通过HttpDataFactory写到磁盘上,然后在删除缓存的HttpContent对象。

@Slf4j
public class HttUploadHandler extends SimpleChannelInboundHandler<HttpObject> { public HttUploadHandler() {
super(false);
} private static final HttpDataFactory factory = new DefaultHttpDataFactory(true);
private static final String FILE_UPLOAD = "/data/";
private static final String URI = "/upload";
private HttpPostRequestDecoder httpDecoder;
HttpRequest request; @Override
protected void channelRead0(final ChannelHandlerContext ctx, final HttpObject httpObject)
throws Exception {
if (httpObject instanceof HttpRequest) {
request = (HttpRequest) httpObject;
if (request.uri().startsWith(URI) && request.method().equals(HttpMethod.POST)) {
httpDecoder = new HttpPostRequestDecoder(factory, request);
httpDecoder.setDiscardThreshold(0);
} else {
//传递给下一个Handler
ctx.fireChannelRead(httpObject);
}
}
if (httpObject instanceof HttpContent) {
if (httpDecoder != null) {
final HttpContent chunk = (HttpContent) httpObject;
httpDecoder.offer(chunk);
if (chunk instanceof LastHttpContent) {
writeChunk(ctx);
//关闭httpDecoder
httpDecoder.destroy();
httpDecoder = null;
}
ReferenceCountUtil.release(httpObject);
} else {
ctx.fireChannelRead(httpObject);
}
} } private void writeChunk(ChannelHandlerContext ctx) throws IOException {
while (httpDecoder.hasNext()) {
InterfaceHttpData data = httpDecoder.next();
if (data != null && HttpDataType.FileUpload.equals(data.getHttpDataType())) {
final FileUpload fileUpload = (FileUpload) data;
final File file = new File(FILE_UPLOAD + fileUpload.getFilename());
log.info("upload file: {}", file);
try (FileChannel inputChannel = new FileInputStream(fileUpload.getFile()).getChannel();
FileChannel outputChannel = new FileOutputStream(file).getChannel()) {
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
ResponseUtil.response(ctx, request, new GeneralResponse(HttpResponseStatus.OK, "SUCCESS", null));
}
}
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.warn("{}", cause);
ctx.channel().close();
} @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (httpDecoder != null) {
httpDecoder.cleanFiles();
}
} }

文件下载

参考官方Demo: https://github.com/netty/netty/blob/4.1/example/src/main/java/io/netty/example/http/file/HttpStaticFileServerHandler.java

做了改动:

  • 为了更高效的传输大数据,实例中用到了ChunkedWriteHandler编码器,它提供了以zero-memory-copy方式写文件。
  • 通过ChannelProgressiveFutureListener对文件下载过程进行监听。
 // 新增ChunkedHandler,主要作用是支持异步发送大的码流(例如大文件传输),但是不占用过多的内存,防止发生java内存溢出错误
ch.pipeline().addLast(new ChunkedWriteHandler());
// 用于下载文件
ch.pipeline().addLast(new HttpDownloadHandler());
@Slf4j
public class HttpDownloadHandler extends SimpleChannelInboundHandler<FullHttpRequest> { public HttpDownloadHandler() {
super(false);
} private String filePath = "/data/body.csv"; @Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
String uri = request.uri();
if (uri.startsWith("/download") && request.method().equals(HttpMethod.GET)) {
GeneralResponse generalResponse = null;
File file = new File(filePath);
try {
final RandomAccessFile raf = new RandomAccessFile(file, "r");
long fileLength = raf.length();
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, fileLength);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream");
response.headers().add(HttpHeaderNames.CONTENT_DISPOSITION, String.format("attachment; filename=\"%s\"", file.getName()));
ctx.write(response);
ChannelFuture sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
@Override
public void operationComplete(ChannelProgressiveFuture future)
throws Exception {
log.info("file {} transfer complete.", file.getName());
raf.close();
} @Override
public void operationProgressed(ChannelProgressiveFuture future,
long progress, long total) throws Exception {
if (total < 0) {
log.warn("file {} transfer progress: {}", file.getName(), progress);
} else {
log.debug("file {} transfer progress: {}/{}", file.getName(), progress, total);
}
}
});
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
} catch (FileNotFoundException e) {
log.warn("file {} not found", file.getPath());
generalResponse = new GeneralResponse(HttpResponseStatus.NOT_FOUND, String.format("file %s not found", file.getPath()), null);
ResponseUtil.response(ctx, request, generalResponse);
} catch (IOException e) {
log.warn("file {} has a IOException: {}", file.getName(), e.getMessage());
generalResponse = new GeneralResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, String.format("读取 file %s 发生异常", filePath), null);
ResponseUtil.response(ctx, request, generalResponse);
}
} else {
ctx.fireChannelRead(request);
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
log.warn("{}", e);
ctx.close(); }
}

下载文件遇到的坑

由于RandomAccessFile是一种文件资源,所以我习惯性的在最后关闭文件资源,采用的是Java7的 try-with-resources 语法,于是问题就出现了,由于 ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); 是异步的,在我关闭RandomAccessFile时,文件还未传输完毕,就会导致下载文件停止。

代码放在: https://github.com/morethink/code/tree/master/java/netty-example

Netty接收HTTP文件上传及文件下载的更多相关文章

  1. struts2的文件上传和文件下载

    实现使用Struts2文件上传和文件下载: 注意点: (1)对应表单的file1和私有成员变量的名称必须一致 <input type="file" name="fi ...

  2. 分享知识-快乐自己:SpringMvc中的单多文件上传及文件下载

    摘要:SpringMvc中的单多文件上传及文件下载:(以下是核心代码(拿过去直接能用)不谢) <!--设置文件上传需要的jar--> <dependency> <grou ...

  3. Struts2文件上传和文件下载

    一.单个文件上传 文件上传需要两个jar包: 首先制作一个简单的页面,用于实现文件上传 <h1>单个文件上传</h1> <s:form action="uplo ...

  4. Struts2 文件上传和文件下载

    一.单个文件上传 文件上传需要两个jar包: 首先制作一个简单的页面,用于实现文件上传 <h1>单个文件上传</h1> <s:form action="uplo ...

  5. struts文件上传、文件下载

    文件上传 如果在表单中上传文件,表单的enctype属性为multipart/form-data struts默认上传文件大小为2M,如果需要修改,在配置文件中设置 <constant name ...

  6. struts2实现文件上传、多文件上传和文件下载

    总结的两个问题,就是struts2上传下载的时候对属性名配置要求非常严格: 第一:上传的时候 private File file; private String fileContentType; pr ...

  7. struts2 笔记02 文件上传、文件下载、类型转换器、国际化的支持

    Struts2的上传 1. Struts2默认采用了apache commons-fileupload  2. Struts2支持三种类型的上传组件 3. 需要引入commons-fileupload ...

  8. Web---演示Servlet的相关类、表单多参数接收、文件上传简单入门

    说明: Servlet的其他相关类: ServletConfig – 代表Servlet的初始化配置参数. ServletContext – 代表整个Web项目. ServletRequest – 代 ...

  9. struts2中的文件上传,文件下载

    文件上传: Servlet中的文件上传回顾 前台页面 1.提交方式post 2.表单类型 multipart/form-data 3.input type=file 表单输入项 后台 apache提交 ...

随机推荐

  1. Prism框架的优点

    以我粗略的了解,prism/mvvm可以做到完全的逻辑和ui分离.即便是事件都是如此.这是主要优点.mvc是从本质上ui框架(当前大量半吊子把业务逻辑写在里面是不对的),mvvm包含客户端的业务逻辑. ...

  2. [百度贴吧]10GB 通信线缆

    现在,即使光纤通信能够带来最低延迟的优势,但是许多IT部门依然在10G以太网(10G bE)中使用铜缆布线,来实现交换机和交换机或者和服务器之间的连接.目前主要有两种主要的铜缆布线技术应用在10 Gb ...

  3. [转帖]Cgroups 与 Systemd

    Cgroups 与 Systemd 大神的文章很牛B .. https://www.cnblogs.com/sparkdev/p/9523194.html 看不太懂 , 转帖一下 自己留着好好看呢. ...

  4. SQL中MAX()和MIN()函数的使用(比较字符串的大小)

    在SQL数据库中,最大/最小值函数—MAX()/MIN()是经常要用到的,下面就将为您分别介绍MAX()函数和MIN()函数的使用,供您参考,希望对您学习SQL数据库能有些帮助. 当需要了解一列中的最 ...

  5. java与C++相比增加和缺少的特性--持续更新

    缺少的特性 java值类型中没有无符号数 java没有运算符重载语法 java中没有struct和union等用户自定义值类型 java中没有虚函数的概念,所有函数默认具有虚函数的特性 java采用单 ...

  6. java 加载过程

    1.main方法进入方法区 2.main方法进栈 3.调用xxx类加载到jvm中 类属性进入数据共享区,方法进入到方法区

  7. P4910 帕秋莉的手环

    题目背景 帕秋莉是蕾米莉亚很早结识的朋友,现在住在红魔馆地下的大图书馆里.不仅擅长许多魔法,还每天都会开发出新的魔法.只是身体比较弱,因为哮喘,会在咏唱符卡时遇到麻烦. 她所用的属性魔法,主要是生命和 ...

  8. BZOJ 1013 | 一份写了一堆注释的高斯消元题解

    题意 给出\(n\)维直角坐标系中\(n + 1\)个点的坐标,它们都在一个\(n\)维球面上,求球心坐标. 题解 设球面上某两个点坐标为\((a_1, a_2, ... a_n)\)和\((b_1, ...

  9. Generate Parentheses - LeetCode

    目录 题目链接 注意点 解法 小结 题目链接 Generate Parentheses - LeetCode 注意点 解法 解法一:递归.当left>right的时候返回(为了防止出现 )( ) ...

  10. Mythological VI

    Description 有\(1...n\)一共\(n\)个数.保证\(n\)为偶数. 小M要把这\(n\)个数两两配对, 一共配成\(n/2\)对.每一对的权值是他们两个数的和. 小M想要知道这\( ...