我已经找到此代码示例
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道如何获取上传的字节总和?
重写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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
使用它而不是standard FileBody,并在上载期间或帖子完成后检索字节数。
| 归档时间: |
|
| 查看次数: |
3713 次 |
| 最近记录: |