Search code examples
javafile-uploadprogressapache-commons-net

Upload in streaming mode and progress information


I'm using a code below to upload file (tens of MB) in streaming mode. Why after fast execution of Util.copyStream(...); (org.apache.commons.net.io.Util) in fact, real uploading is still taking place (a longer time) ? How to better measure progress of uploading in that mode (is possible) ?

/**
 * 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();
    }
}

Solution

  • Found solution: connection.setFixedLengthStreamingMode((int) videoFile.length()); do the trick.