如何使用Undertow返回用Java下载的文件?

问题描述 投票:2回答:1

我试图让我的游戏客户端下载客户端运行所需的缓存。在我的游戏网络服务器里面我这样做:

@RouteManifest(template="/cache", method="GET")
public class APICacheRoute extends RouteHttpHandler<JadePreprocessor> {
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        Path path = Paths.get("./cache/Alterscape.zip");
        File file = path.toFile();
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");
        exchange.getResponseSender().send(file);
    }
}

但是,我收到错误,该文件必须是ByteBuffer。如何返回要下载的文件?

我的Web服务器看起来像这样:

public static void initialize() {
    ServerController server = new ServerController("localhost", 8080, 8443);
    server.register(new APIVirtualHost());
    server.inititialize();
}

我的APIVirtualHost看起来像这样:

public APIVirtualHost() {
    super(127.0.0.1);
    setDirectoryListingEnabled(false);
}
java web undertow
1个回答
1
投票

使用Undertow,您需要从I / O线程调度处理程序以使用阻塞操作。您需要在需要执行阻止操作时执行此操作,例如读取请求正文,接受文件上载流,当然还有发送文件。

在handle()方法的顶部,使用此方法将请求分派给阻塞线程,并关闭非阻塞I / O线程:

if (serverExchange.isInIoThread()) {
    serverExchange.dispatch(this);
    return;
}

然后在准备发送缓冲区时开始阻止:

serverExchange.startBlocking();

然后发送文件,您可以使用缓冲流:

serverExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");

final File file = new File("/location/to/your/file");
final OutputStream outputStream = serverExchange.getOutputStream();
final InputStream inputStream = new FileInputStream(file);

byte[] buf = new byte[8192];
int c;
while ((c = inputStream.read(buf, 0, buf.length)) > 0) {
    outputStream.write(buf, 0, c);
    outputStream.flush();
}

outputStream.close();
inputStream.close();

send对象上的ServerExchange方法用于使用非阻塞方法发送响应数据 - 适用于文本或JSON。 ByteBuffer参数重载用于发送原始字节数据,这是Undertow在发送时将字符串转换为的内容。这可能有点误导。

快乐的编码。

© www.soinside.com 2019 - 2024. All rights reserved.