HttpClient上传大文件并显示发送的字节数 [英] HttpClient upload big file and show sent bytes number
本文介绍了HttpClient上传大文件并显示发送的字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找到了这个代码示例
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();
}
}
我只是想知道如何获得上传的字节总和?
I am just wondering how to get uploaded bytes sum?
推荐答案
覆盖 FileBody.writeTo(OutputStream)
计算字节数写的。这允许在上传期间和完成之后发送的字节数(即使被中断)。
Override FileBody.writeTo(OutputStream)
to counts bytes as they are written. This allows a count of bytes sent (even if interrupted), both during the upload and after it is complete.
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
,并在上传期间或帖子完成后检索字节数。
Use that instead of the standard FileBody
, and retrieve the bytecount during upload, or after the post has completed.
这篇关于HttpClient上传大文件并显示发送的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文