【问题标题】:Upload in streaming mode and progress information以流模式上传和进度信息
【发布时间】:2012-02-24 04:04:27
【问题描述】:

我正在使用下面的代码以流模式上传文件(数十 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();
    }
}

【问题讨论】:

  • 你有没有试过实现bytesTransferred(CopyStreamEvent event)的body?

标签: java file-upload progress apache-commons-net


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 2016-08-18
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多