我有以下用于使用 Apache 的 HTTP-Client (org.apache.http.client) 上传文件的代码:
public static void main(String[] args) throws Exception
{
String fileName = "test.avi";
File file = new File(fileName);
String serverResponse = null;
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPut put = new HttpPut("http://localhost:8080/" + fileName);
FileEntity fileEntity = new FileEntity(file, "binary/octet-stream");
put.setEntity(fileEntity);
HttpResponse response = client.execute(put);
HttpEntity entity = response.getEntity();
if (entity != null)
{
serverResponse = EntityUtils.toString(entity);
System.out.println(serverResponse);
}
}
它工作得很好,但现在我想要一个进度条来显示文件上传的进度。这是怎么做到的呢?我在以下位置找到了一个代码片段使用Java上传文件(带进度条) https://stackoverflow.com/questions/254719/file-upload-with-java-with-progress-bar但它是为 Apache HTTP Client 3 (org.apache.commons.httpclient) 设计的,并且 Apache HTTP Client 4 中不存在 RequestEntity 类。;(
也许你们有人有办法?
许多问候
Benny
我引入了一个派生FileEntity
只计算写入的字节数。
它用OutputStreamProgress
进行实际计数(有点像装饰者到实际的OutputStream
).
The 优势这个(以及一般的装饰)是我做的not需要复制实际的实现,例如从文件流到输出流的实际复制。我还可以更改为使用不同的(更新的)实现,例如NFileEntity
.
Enjoy...
文件实体.java
public class FileEntity extends org.apache.http.entity.FileEntity {
private OutputStreamProgress outstream;
public FileEntity(File file, String contentType) {
super(file, contentType);
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
this.outstream = new OutputStreamProgress(outstream);
super.writeTo(this.outstream);
}
/**
* Progress: 0-100
*/
public int getProgress() {
if (outstream == null) {
return 0;
}
long contentLength = getContentLength();
if (contentLength <= 0) { // Prevent division by zero and negative values
return 0;
}
long writtenLength = outstream.getWrittenLength();
return (int) (100*writtenLength/contentLength);
}
}
OutputStreamProgress.java
public class OutputStreamProgress extends OutputStream {
private final OutputStream outstream;
private volatile long bytesWritten=0;
public OutputStreamProgress(OutputStream outstream) {
this.outstream = outstream;
}
@Override
public void write(int b) throws IOException {
outstream.write(b);
bytesWritten++;
}
@Override
public void write(byte[] b) throws IOException {
outstream.write(b);
bytesWritten += b.length;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
outstream.write(b, off, len);
bytesWritten += len;
}
@Override
public void flush() throws IOException {
outstream.flush();
}
@Override
public void close() throws IOException {
outstream.close();
}
public long getWrittenLength() {
return bytesWritten;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)