java HttpServer在HttpHandler中接收大文件

时间:2019-01-03 09:55:34

标签: java file http httpserver

我正在为我的应用程序构建一个快速HTTP服务器,并且需要接收一个大文件(7z存档-250MB至1GB)。

服务器基于com.sun.net.httpserver.HttpServercom.sun.net.httpserver.HttpHandler

到目前为止,我进行了以下操作,这些操作显然不起作用-它可以接收44个字节并完成操作。

@Override
public void handle(HttpExchange httpExchange) throws IOException
{
    String requestMethod = httpExchange.getRequestMethod();

    if (requestMethod.equalsIgnoreCase("POST"))
    {
        Headers responseHeaders = httpExchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/plain");
        httpExchange.sendResponseHeaders(200, 0);

        InputStream inputStream = httpExchange.getRequestBody();
        byte[] buffer = new byte[4096];
        int lengthRead;
        int lengthTotal = 0;
        FileOutputStream fileOutputStream = new FileOutputStream(FILENAME);

        while ((lengthRead = inputStream.read(buffer, 0, 4096)) > 0)
        {
            fileOutputStream.write(buffer, 0, lengthRead);
            lengthTotal += lengthRead;
        }

        fileOutputStream.close();

        System.out.println("File uploaded - " + lengthTotal + " bytes total.");

        httpExchange.getResponseBody().close();
    }
}

请求如下所示: enter image description here

我如何收到文件?

0 个答案:

没有答案