0

我正在使用下面的代码以流模式上传文件(数十 MB)。为什么实际上在快速执行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();
    }
}
4

1 回答 1

0

找到解决方案:解决问题connection.setFixedLengthStreamingMode((int) videoFile.length());

于 2012-02-22T05:43:18.513 回答