【Netty基础】基于HTTP的文件下载Server实例


功能描述:打开浏览器,可实现文件下载功能

例:

public class HttpDownLoadFileServer {

    private static final String DEFAULT_URL = "/src/image/";

    public void run(final int port, final String url) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch)
                    throws Exception {
                    ch.pipeline().addLast("http-decoder",
                        new HttpRequestDecoder());
                    ch.pipeline().addLast("http-aggregator",
                        new HttpObjectAggregator(65536));
                    ch.pipeline().addLast("http-encoder",
                        new HttpResponseEncoder());
                    ch.pipeline().addLast("http-chunked",
                        new ChunkedWriteHandler());
                    ch.pipeline().addLast("fileServerHandler",
                        new HttpDownLoadFileServerHandler(url));
                }
                });
            ChannelFuture future = b.bind(port).sync();
            System.out.println("HTTP文件目录服务器启动,网址是 : " + "http://127.0.0.1:"
                + port + url);
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
    int port = 8080;
    if (args.length > 0) {
        try {
        port = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
        e.printStackTrace();
        }
    }
    String url = DEFAULT_URL;
    if (args.length > 1)
        url = args[1];
    new HttpDownLoadFileServer().run(port, url);
    }
}

HttpDownLoadFileServerHandler类

public class HttpDownLoadFileServerHandler extends
    SimpleChannelInboundHandler<FullHttpRequest> {
    private final String url;

    public HttpDownLoadFileServerHandler(String url) {
    this.url = url;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx,
        FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final String uri = request.uri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
        sendListing(ctx, file);
        } else {
        sendRedirect(ctx, uri + '/');
        }
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");// 以只读的方式打开文件
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = randomAccessFile.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ChannelFuture sendFileFuture;
    sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0,
        fileLength, 8192), ctx.newProgressivePromise());
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future,
            long progress, long total) {
        if (total < 0) { // total unknown
            System.err.println("Transfer progress: " + progress);
        } else {
            System.err.println("Transfer progress: " + progress + " / "
                + total);
        }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future)
            throws Exception {
        System.out.println("Transfer complete.");
        }
    });
    ChannelFuture lastContentFuture = ctx
        .writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
    cause.printStackTrace();
    if (ctx.channel().isActive()) {
        sendError(ctx, INTERNAL_SERVER_ERROR);
    }
    }

    private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");

    private String sanitizeUri(String uri) {
    try {
        uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        try {
        uri = URLDecoder.decode(uri, "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
        throw new Error();
        }
    }
    if (!uri.startsWith(url)) {
        return null;
    }
    if (!uri.startsWith("/")) {
        return null;
    }
    //    将 '/' 换为 '\'
    uri = uri.replace('/', File.separatorChar);
    if (uri.contains(File.separator + '.')
        || uri.contains('.' + File.separator) || uri.startsWith(".")
        || uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) {
        return null;
    }
    // System.getProperty("user.dir")) = E:\IDEA\workspace
    // File.separator  =  \
    return System.getProperty("user.dir") + File.separator + uri;
    }

    private static final Pattern ALLOWED_FILE_NAME = Pattern
        .compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");

    private static void sendListing(ChannelHandlerContext ctx, File dir) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    StringBuilder buf = new StringBuilder();
    String dirPath = dir.getPath();
    buf.append("<!DOCTYPE html>\r\n");
    buf.append("<html><head><title>");
    buf.append(dirPath);
    buf.append(" 目录:");
    buf.append("</title></head><body>\r\n");
    buf.append("<h3>");
    buf.append(dirPath).append(" 目录:");
    buf.append("</h3>\r\n");
    buf.append("<ul>");
    buf.append("<li>链接:<a href=\"../\">..</a></li>\r\n");
    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
        continue;
        }
        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
        continue;
        }
        buf.append("<li>链接:<a href=\"");
        buf.append(name);
        buf.append("\">");
        buf.append(name);
        buf.append("</a></li>\r\n");
    }
    buf.append("</ul></body></html>\r\n");
    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
    response.headers().set(LOCATION, newUri);
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void sendError(ChannelHandlerContext ctx,
        HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
        status, Unpooled.copiedBuffer("Failure: " + status.toString()
            + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void setContentTypeHeader(HttpResponse response, File file) {
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    response.headers().set(CONTENT_TYPE,
        mimeTypesMap.getContentType(file.getPath()));
    }
}

注:运行程序,打开浏览器,输入http://127.0.0.1:8080/src/image/即可

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值