【问题标题】:HttpClient upload big file and show sent bytes numberHttpClient上传大文件并显示发送字节数
【发布时间】:2011-07-14 18:02:01
【问题描述】:

我找到了这个代码示例

import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

我只是想知道如何获取上传的字节总数?

【问题讨论】:

  • 您是在寻找File 的大小,还是整个 POST 的大小(只会大一点)?
  • 不,我想知道上传了多少字节。在控制台中显示数字

标签: java http


【解决方案1】:

覆盖FileBody.writeTo(OutputStream) 以在写入字节时对其进行计数。这允许在上传期间和上传完成后计算发送的字节数(即使被中断)。

public class FileBodyCounter extends FileBody {
    private volatile long byteCount;

    public long getBytesWritten() {
        return byteCount;
    }

    public void writeTo(OutputStream out) {
        super.writeTo(new FilterOutputStream(out) {
            // Other write() methods omitted for brevity. Implement for better performance
            public void write(int b) throws IOException {
                byteCount++;
                super.write(b);
            }
        });
    }
}

使用它代替标准的FileBody,并在上传期间或发布完成后检索字节数。

【讨论】:

  • 我想查看上传进程号。我的意思不是在之后而是在 :)
  • 如上所述,您可以在上传期间访问写入的字节数。只需让上传在一个线程上进行,然后在另一个线程上调用FileBodyCountergetBytesWritten() 方法。
  • 谢谢,我会的,但我对 MultiPartEntity 感兴趣以获取上传进度。我找到了很多例子:)
猜你喜欢
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多