Загрузить в потоковом режиме и информацию о прогрессе - PullRequest
0 голосов
/ 01 февраля 2012

Я использую код ниже для загрузки файла (десятки МБ) в потоковом режиме.Почему после быстрого выполнения Util.copyStream(...); (org.apache.commons.net.io.Util) фактически, настоящая загрузка все еще происходит (более длительное время)?Как лучше измерить ход загрузки в этом режиме (возможно)?

/**
 * upload file (streaming)
 * @param endpoint
 */
private void doPut(String endpoint) {
    URL endpointUrl;
    HttpURLConnection connection;
    try {
        File videoFile = new File(videoPath);
        endpointUrl = new URL(endpoint);
        connection = (HttpURLConnection) endpointUrl.openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Length", videoFile.length()+"");
        connection.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(videoFile));
        connection.setDoOutput(true);

        CopyStreamListener listener = new CopyStreamListener() {
            public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
                System.out.printf("\r%-30S: %d / %d", "Sent", totalBytesTransferred, streamSize);
            }
            public void bytesTransferred(CopyStreamEvent event) {
            }
        };
        InputStream in = new FileInputStream(videoFile);
        OutputStream out = connection.getOutputStream();
        System.out.println("Uploading \""+videoFile.getAbsolutePath()+"\"... ");
        long c = Util.copyStream(in, out, Util.DEFAULT_COPY_BUFFER_SIZE, videoFile.length(), listener);
        System.out.printf("\n%-30S: %d\n", "Bytes sent", c);
        in.close();
        out.close();

        // at this point uploading is still taking place...

        // return code
        System.out.printf("\n%-30S: %d\n", "Response code", connection.getResponseCode());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 Ответ

0 голосов
/ 22 февраля 2012

Найденное решение: connection.setFixedLengthStreamingMode((int) videoFile.length()); добиваться цели.

...