io.netty.handler.stream.ChunkedFile Java Examples

The following examples show how to use io.netty.handler.stream.ChunkedFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StreamServerGroupHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
private void sendFile(ChannelHandlerContext ctx, String fileUri, String contentType) throws IOException {
    logger.debug("file is :{}", fileUri);
    File file = new File(fileUri);
    ChunkedFile chunkedFile = new ChunkedFile(file);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, chunkedFile.length());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(chunkedFile);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example #2
Source File: RequestHandler.java    From netty-rest-server with Apache License 2.0 5 votes vote down vote up
/**
 * 输出文件响应
 * 
 * @param responseEntity
 * @return
 * @throws IOException
 */
private ChannelFuture writeFileResponse(ResponseEntity<?> responseEntity) throws IOException {
    RandomAccessFile raf = (RandomAccessFile) responseEntity.getBody();
    long fileLength = raf.length();
    
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpUtil.setContentLength(response, fileLength);
    if(responseEntity.getMimetype() != null && !responseEntity.getMimetype().trim().equals("")) {
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, responseEntity.getMimetype());
    }
    if(responseEntity.getFileName() != null && !responseEntity.getFileName().trim().equals("")) {
        String fileName = new String(responseEntity.getFileName().getBytes("gb2312"), "ISO8859-1");
        response.headers().set(HttpHeaderNames.CONTENT_DISPOSITION, "attachment; filename=" + fileName); 
    }
    if (HttpUtil.isKeepAlive(HttpContextHolder.getRequest())) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    
    ChannelHandlerContext ctx = HttpContextHolder.getResponse().getChannelHandlerContext();
    ctx.write(response);
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture = null;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture =
                ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }
    return lastContentFuture;
}
 
Example #3
Source File: StreamServerHandler.java    From IpCamera with Eclipse Public License 2.0 5 votes vote down vote up
private void sendFile(ChannelHandlerContext ctx, String fileUri, String contentType) throws IOException {
    File file = new File(ipCameraHandler.config.get(CONFIG_FFMPEG_OUTPUT).toString() + fileUri);
    ChunkedFile chunkedFile = new ChunkedFile(file);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, chunkedFile.length());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(chunkedFile);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example #4
Source File: HttpDataServerHandler.java    From tajo with Apache License 2.0 5 votes vote down vote up
private ChannelFuture sendFile(ChannelHandlerContext ctx,
                               FileChunk file) throws IOException {
  RandomAccessFile raf;
  try {
    raf = new RandomAccessFile(file.getFile(), "r");
  } catch (FileNotFoundException fnfe) {
    return null;
  }

  ChannelFuture writeFuture;
  ChannelFuture lastContentFuture;
  if (ctx.pipeline().get(SslHandler.class) != null) {
    // Cannot use zero-copy with HTTPS.
    lastContentFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, file.startOffset(),
        file.length(), 8192)));
  } else {
    // No encryption - use zero-copy.
    final FileRegion region = new DefaultFileRegion(raf.getChannel(),
        file.startOffset(), file.length());
    writeFuture = ctx.write(region);
    lastContentFuture = ctx.write(LastHttpContent.EMPTY_LAST_CONTENT);
    writeFuture.addListener(new ChannelFutureListener() {
      public void operationComplete(ChannelFuture future) {
        if (region.refCnt() > 0) {
          region.release();
        }
      }
    });
  }

  return lastContentFuture;
}
 
Example #5
Source File: NettyTransport.java    From jzab with Apache License 2.0 5 votes vote down vote up
void sendFile(File file) throws Exception {
  long length = file.length();
  LOG.debug("Got request of sending file {} of length {}.",
            file, length);
  Message handshake = MessageBuilder.buildFileHeader(length);
  byte[] bytes = handshake.toByteArray();
  // Sends HANDSHAKE first before transferring actual file data, the
  // HANDSHAKE will tell the peer's channel to prepare for the file
  // transferring.
  channel.writeAndFlush(Unpooled.wrappedBuffer(bytes)).sync();
  ChannelHandler prepender = channel.pipeline().get("frameEncoder");
  // Removes length prepender, we don't need this handler for file
  // transferring.
  channel.pipeline().remove(prepender);
  // Adds ChunkedWriteHandler for file transferring.
  ChannelHandler cwh = new ChunkedWriteHandler();
  channel.pipeline().addLast(cwh);
  // Begins file transferring.
  RandomAccessFile raf = new RandomAccessFile(file, "r");
  if (channel.pipeline().get(SslHandler.class) != null) {
    // Zero-Copy file transferring is not supported for ssl.
    channel.writeAndFlush(new ChunkedFile(raf, 0, length, 8912));
  } else {
    // Use Zero-Copy file transferring in non-ssl mode.
    FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, length);
    channel.writeAndFlush(region);
  }
  // Restores pipeline to original state.
  channel.pipeline().remove(cwh);
  channel.pipeline().addLast("frameEncoder", prepender);
}
 
Example #6
Source File: HttpChunkedInputTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Test
public void testChunkedFile() throws IOException {
    check(new HttpChunkedInput(new ChunkedFile(TMP)));
}
 
Example #7
Source File: FileView.java    From Summer with Apache License 2.0 4 votes vote down vote up
@Override
public ChunkedInput<ByteBuf> getChunkedInput() throws IOException {
	return new ChunkedFile(file);
}
 
Example #8
Source File: HttpChunkedInputTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Test
public void testChunkedFile() throws IOException {
    check(new HttpChunkedInput(new ChunkedFile(TMP)));
}