我找到了这个代码示例
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();
}
}
我只是想知道如何获取上传的字节数?
最佳答案
覆盖 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
,并在上传期间或发布完成后检索字节数。
关于java - HttpClient 上传大文件并显示发送的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5294532/