這個處理器的原理是接收HttpObject對象,按照HttpRequest,HttpContent來作處理,文件內容是在HttpContent消息帶來的。java
而後在HttpContent中一個chunk一個chunk讀,chunk大小能夠在初始化HttpServerCodec時設置。將每一個chunk交個httpDecoder複製一份,當讀到LastHttpContent對象時,代表上傳結束,能夠將httpDecoder中緩存的文件經過HttpDataFactory寫到磁盤上,而後在刪除緩存的HttpContent對象。git
@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: github.com/netty/netty…github
作了改動:緩存
// 新增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
時,文件還未傳輸完畢,就會致使下載文件中止。app
代碼放在: github.com/morethink/c…dom