如何获得一个文件的上传与Apache HttpClient的4进度条
推荐于2016-01-02 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517181
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
1. 我介绍一个派生FileEntity只是计数写入的字节。OutputStreamProgress做了实际的计数(一种装饰器的实际OutputStream)。 这样做的好处(与装修一般)是,我不需要从文件流复制的实际就像实际的复制到输出流。我也可以改变一个不同的(新)之类的NFileEntity。 享受... FileEntity.javapublic 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.javapublic 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;
}
}
2. 这个答案通过添加一个简单的监听器OutputStreamProgress.java类,而不是由公众getProgress()方法(我真的不知道你是如何想调用getProgress()方法,因为该线程会执行内部延伸kilaka的回答的HttpClient的代码,整个你可能需要调用getProgress()!)。 请注意,您需要延长您希望每个实体类型的实体类,当你写你的HttpClient代码,你需要创建一个新的类型的实体。 我写了一个非常基本的写听者的WriteListener接口。在这里,您将添加你的逻辑做从OutputStreamProgress写报告,如更新一个进度条:) 非常感谢kilaka装饰理念在点票outstream潜行。 WriteLisener.javapublic interface WriteListener {
void registerWrite(long amountOfBytesWritten);
}
OutputStreamProgress.javaimport java.io.IOException;
import java.io.OutputStream;
public class OutputStreamProgress extends OutputStream {
private final OutputStream outstream;
private long bytesWritten=0;
private final WriteListener writeListener;
public OutputStreamProgress(OutputStream outstream, WriteListener writeListener) {
this.outstream = outstream;
this.writeListener = writeListener;
}
@Override
public void write(int b) throws IOException {
outstream.write(b);
bytesWritten++;
writeListener.registerWrite(bytesWritten);
}
@Override
public void write(byte[] b) throws IOException {
outstream.write(b);
bytesWritten += b.length;
writeListener.registerWrite(bytesWritten);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
outstream.write(b, off, len);
bytesWritten += len;
writeListener.registerWrite(bytesWritten);
}
@Override
public void flush() throws IOException {
outstream.flush();
}
@Override
public void close() throws IOException {
outstream.close();
}
}
BasicWriteListenerpublic class BasicWriteListener implements WriteListener {
public BasicWriteListener() {
// TODO Auto-generated constructor stub
}
public void registerWrite(long amountOfBytesWritten) {
System.out.println(amountOfBytesWritten);
}
}
MultipartEntityWithProgressBarimport java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
public class MultipartEntityWithProgressBar extends MultipartEntity {
private OutputStreamProgress outstream;
private WriteListener writeListener;
@Override
public void writeTo(OutputStream outstream) throws IOException {
this.outstream = new OutputStreamProgress(outstream, writeListener);
super.writeTo(this.outstream);
}
public MultipartEntityWithProgressBar(WriteListener writeListener)
{
super();
this.writeListener = writeListener;
}
public MultipartEntityWithProgressBar(HttpMultipartMode mode, WriteListener writeListener)
{
super(mode);
this.writeListener = writeListener;
}
public MultipartEntityWithProgressBar(HttpMultipartMode mode, String boundary, Charset charset, WriteListener writeListener)
{
super(mode, boundary, charset);
this.writeListener = writeListener;
}
// Left in for clarity to show where I took from kilaka's answer
// /**
// * 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);
// }
}
3. 一个新的包组织结构。从公地-10(2.4)和它的类CountingOutputStream。 我改变了最初的代码,以反映我的项目需要一个多形式输入,(这个会费的征收服务器端)。 想想看,大文件的增量在我的测试中对应于4096个字节。该counterChanged()被调用传输的数据的每4096字节,什么是可以接受的情况。 看起来像:public void post(String url, File sendFile) {
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url + "/" + sendFile.getName());
MultipartEntity multiEntity = new MultipartEntity();
MyFileBody fileBody = new MyFileBody(sendFile);
fileBody.setListener(new IStreamListener(){
@Override
public void counterChanged(int delta) {
// do something
System.out.println(delta);
}});
multiEntity.addPart("file", fileBody);
StringBody stringBody = new StringBody(sendFile.getName());
multiEntity.addPart("fileName", stringBody);
post.setEntity(multiEntity);
HttpResponse response = client.execute(post);
}
类MyFileBodypublic class MyFileBody extends FileBody {
private IStreamListener listener;
public MyFileBody(File file) {
super(file);
}
@Override
public void writeTo(OutputStream out) throws IOException {
CountingOutputStream output = new CountingOutputStream(out) {
@Override
protected void beforeWrite(int n) {
if (listener != null && n != 0)
listener.counterChanged(n);
super.beforeWrite(n);
}
};
super.writeTo(output);
}
public void setListener(IStreamListener listener) {
this.listener = listener;
}
public IStreamListener getListener() {
return listener;
}
}
最后,监听器接口的样子:public interface IStreamListener {
void counterChanged(int delta);
}
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.javapublic 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;
}
}
2. 这个答案通过添加一个简单的监听器OutputStreamProgress.java类,而不是由公众getProgress()方法(我真的不知道你是如何想调用getProgress()方法,因为该线程会执行内部延伸kilaka的回答的HttpClient的代码,整个你可能需要调用getProgress()!)。 请注意,您需要延长您希望每个实体类型的实体类,当你写你的HttpClient代码,你需要创建一个新的类型的实体。 我写了一个非常基本的写听者的WriteListener接口。在这里,您将添加你的逻辑做从OutputStreamProgress写报告,如更新一个进度条:) 非常感谢kilaka装饰理念在点票outstream潜行。 WriteLisener.javapublic interface WriteListener {
void registerWrite(long amountOfBytesWritten);
}
OutputStreamProgress.javaimport java.io.IOException;
import java.io.OutputStream;
public class OutputStreamProgress extends OutputStream {
private final OutputStream outstream;
private long bytesWritten=0;
private final WriteListener writeListener;
public OutputStreamProgress(OutputStream outstream, WriteListener writeListener) {
this.outstream = outstream;
this.writeListener = writeListener;
}
@Override
public void write(int b) throws IOException {
outstream.write(b);
bytesWritten++;
writeListener.registerWrite(bytesWritten);
}
@Override
public void write(byte[] b) throws IOException {
outstream.write(b);
bytesWritten += b.length;
writeListener.registerWrite(bytesWritten);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
outstream.write(b, off, len);
bytesWritten += len;
writeListener.registerWrite(bytesWritten);
}
@Override
public void flush() throws IOException {
outstream.flush();
}
@Override
public void close() throws IOException {
outstream.close();
}
}
BasicWriteListenerpublic class BasicWriteListener implements WriteListener {
public BasicWriteListener() {
// TODO Auto-generated constructor stub
}
public void registerWrite(long amountOfBytesWritten) {
System.out.println(amountOfBytesWritten);
}
}
MultipartEntityWithProgressBarimport java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
public class MultipartEntityWithProgressBar extends MultipartEntity {
private OutputStreamProgress outstream;
private WriteListener writeListener;
@Override
public void writeTo(OutputStream outstream) throws IOException {
this.outstream = new OutputStreamProgress(outstream, writeListener);
super.writeTo(this.outstream);
}
public MultipartEntityWithProgressBar(WriteListener writeListener)
{
super();
this.writeListener = writeListener;
}
public MultipartEntityWithProgressBar(HttpMultipartMode mode, WriteListener writeListener)
{
super(mode);
this.writeListener = writeListener;
}
public MultipartEntityWithProgressBar(HttpMultipartMode mode, String boundary, Charset charset, WriteListener writeListener)
{
super(mode, boundary, charset);
this.writeListener = writeListener;
}
// Left in for clarity to show where I took from kilaka's answer
// /**
// * 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);
// }
}
3. 一个新的包组织结构。从公地-10(2.4)和它的类CountingOutputStream。 我改变了最初的代码,以反映我的项目需要一个多形式输入,(这个会费的征收服务器端)。 想想看,大文件的增量在我的测试中对应于4096个字节。该counterChanged()被调用传输的数据的每4096字节,什么是可以接受的情况。 看起来像:public void post(String url, File sendFile) {
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url + "/" + sendFile.getName());
MultipartEntity multiEntity = new MultipartEntity();
MyFileBody fileBody = new MyFileBody(sendFile);
fileBody.setListener(new IStreamListener(){
@Override
public void counterChanged(int delta) {
// do something
System.out.println(delta);
}});
multiEntity.addPart("file", fileBody);
StringBody stringBody = new StringBody(sendFile.getName());
multiEntity.addPart("fileName", stringBody);
post.setEntity(multiEntity);
HttpResponse response = client.execute(post);
}
类MyFileBodypublic class MyFileBody extends FileBody {
private IStreamListener listener;
public MyFileBody(File file) {
super(file);
}
@Override
public void writeTo(OutputStream out) throws IOException {
CountingOutputStream output = new CountingOutputStream(out) {
@Override
protected void beforeWrite(int n) {
if (listener != null && n != 0)
listener.counterChanged(n);
super.beforeWrite(n);
}
};
super.writeTo(output);
}
public void setListener(IStreamListener listener) {
this.listener = listener;
}
public IStreamListener getListener() {
return listener;
}
}
最后,监听器接口的样子:public interface IStreamListener {
void counterChanged(int delta);
}
展开全部
写个类继承FileBody重写writeto方法
@Override
public void writeTo(final OutputStream out) throws IOException {
Args.notNull(out, "Output stream");
final InputStream in = new FileInputStream(this.file);
try {
final byte[] tmp = new byte[4096];
int l;
int i=0;
int totalcount=(int) (this.file.length()/4096);
while ((l = in.read(tmp)) != -1) {
i++;
out.write(tmp, 0, l);
System.out.println("upload process is "+i+"/"+totalcount);
}
out.flush();
} finally {
in.close();
}
}
@Override
public void writeTo(final OutputStream out) throws IOException {
Args.notNull(out, "Output stream");
final InputStream in = new FileInputStream(this.file);
try {
final byte[] tmp = new byte[4096];
int l;
int i=0;
int totalcount=(int) (this.file.length()/4096);
while ((l = in.read(tmp)) != -1) {
i++;
out.write(tmp, 0, l);
System.out.println("upload process is "+i+"/"+totalcount);
}
out.flush();
} finally {
in.close();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询