Android带进度条文件上传

Being able to display a progress bar during a time consuming upload to a web server is important when dealing with users and appeasing their impatience. Here is one approach of achieving this.

In this example we are going to use 2 classes – the first one is going to implement Android’s really handy threading function: Async Task and the other is going to extend MutlipartEntity – the basic object used for a multipart POST. Let’s take a look at extending a MultipartEntity object:

 

CustomMultiPartEntity.java

 

  1. import java.io.FilterOutputStream;  
  2. import java.io.IOException;  
  3. import java.io.OutputStream;  
  4. import java.nio.charset.Charset;  
  5. import org.apache.http.entity.mime.HttpMultipartMode;  
  6. import org.apache.http.entity.mime.MultipartEntity;  
  7.    
  8. public class CustomMultiPartEntity extends MultipartEntity  
  9. {  
  10.    
  11.     private final ProgressListener listener;  
  12.    
  13.     public CustomMultiPartEntity(final ProgressListener listener)  
  14.     {  
  15.         super();  
  16.         this.listener = listener;  
  17.     }  
  18.    
  19.     public CustomMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener)  
  20.     {  
  21.         super(mode);  
  22.         this.listener = listener;  
  23.     }  
  24.    
  25.     public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)  
  26.     {  
  27.         super(mode, boundary, charset);  
  28.         this.listener = listener;  
  29.     }  
  30.    
  31.     @Override  
  32.     public void writeTo(final OutputStream outstream) throws IOException  
  33.     {  
  34.         super.writeTo(new CountingOutputStream(outstream, this.listener));  
  35.     }  
  36.    
  37.     public static interface ProgressListener  
  38.     {  
  39.         void transferred(long num);  
  40.     }  
  41.    
  42.     public static class CountingOutputStream extends FilterOutputStream  
  43.     {  
  44.    
  45.         private final ProgressListener listener;  
  46.         private long transferred;  
  47.    
  48.         public CountingOutputStream(final OutputStream out, final ProgressListener listener)  
  49.         {  
  50.             super(out);  
  51.             this.listener = listener;  
  52.             this.transferred = 0;  
  53.         }  
  54.    
  55.         public void write(byte[] b, int off, int len) throws IOException  
  56.         {  
  57.             out.write(b, off, len);  
  58.             this.transferred += len;  
  59.             this.listener.transferred(this.transferred);  
  60.         }  
  61.    
  62.         public void write(int b) throws IOException  
  63.         {  
  64.             out.write(b);  
  65.             this.transferred++;  
  66.             this.listener.transferred(this.transferred);  
  67.         }  
  68.     }  
  69. }  
import java.io.FilterOutputStream;
import 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 CustomMultiPartEntity extends MultipartEntity
{
 
	private final ProgressListener listener;
 
	public CustomMultiPartEntity(final ProgressListener listener)
	{
		super();
		this.listener = listener;
	}
 
	public CustomMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener)
	{
		super(mode);
		this.listener = listener;
	}
 
	public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)
	{
		super(mode, boundary, charset);
		this.listener = listener;
	}
 
	@Override
	public void writeTo(final OutputStream outstream) throws IOException
	{
		super.writeTo(new CountingOutputStream(outstream, this.listener));
	}
 
	public static interface ProgressListener
	{
		void transferred(long num);
	}
 
	public static class CountingOutputStream extends FilterOutputStream
	{
 
		private final ProgressListener listener;
		private long transferred;
 
		public CountingOutputStream(final OutputStream out, final ProgressListener listener)
		{
			super(out);
			this.listener = listener;
			this.transferred = 0;
		}
 
		public void write(byte[] b, int off, int len) throws IOException
		{
			out.write(b, off, len);
			this.transferred += len;
			this.listener.transferred(this.transferred);
		}
 
		public void write(int b) throws IOException
		{
			out.write(b);
			this.transferred++;
			this.listener.transferred(this.transferred);
		}
	}
}


By simply counting the amount of bytes that are written, we can implement an interface (here we called it trasnfered())which can be called in our main class to update our progress bar dialog box:

 

Main.java

 

  1. class HttpMultipartPost extends AsyncTask<HttpResponse, Integer, TypeUploadImage>  
  2.     {  
  3.         ProgressDialog pd;  
  4.         long totalSize;  
  5.    
  6.         @Override  
  7.         protected void onPreExecute()  
  8.         {  
  9.             pd = new ProgressDialog(this);  
  10.             pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  11.             pd.setMessage("Uploading Picture...");  
  12.             pd.setCancelable(false);  
  13.             pd.show();  
  14.         }  
  15.    
  16.         @Override  
  17.         protected TypeUploadImage doInBackground(HttpResponse... arg0)  
  18.         {  
  19.             HttpClient httpClient = new DefaultHttpClient();  
  20.             HttpContext httpContext = new BasicHttpContext();  
  21.             HttpPost httpPost = new HttpPost("http://herpderp.com/UploadImage.php");  
  22.    
  23.             try  
  24.             {  
  25.                 CustomMultipartEntity multipartContent = new CustomMultipartEntity(new ProgressListener()  
  26.                 {  
  27.                     @Override  
  28.                     public void transferred(long num)  
  29.                     {  
  30.                         publishProgress((int) ((num / (float) totalSize) * 100));  
  31.                     }  
  32.                 });  
  33.    
  34.                 // We use FileBody to transfer an image   
  35.                 multipartContent.addPart("uploaded_file"new FileBody(new File(m_userSelectedImagePath)));  
  36.                 totalSize = multipartContent.getContentLength();  
  37.    
  38.                 // Send it   
  39.                 httpPost.setEntity(multipartContent);  
  40.                 HttpResponse response = httpClient.execute(httpPost, httpContext);  
  41.                 String serverResponse = EntityUtils.toString(response.getEntity());  
  42.    
  43.                 ResponseFactory rp = new ResponseFactory(serverResponse);  
  44.                 return (TypeImage) rp.getData();  
  45.             }  
  46.    
  47.             catch (Exception e)  
  48.             {  
  49.                 System.out.println(e);  
  50.             }  
  51.             return null;  
  52.         }  
  53.    
  54.         @Override  
  55.         protected void onProgressUpdate(Integer... progress)  
  56.         {  
  57.             pd.setProgress((int) (progress[0]));  
  58.         }  
  59.    
  60.         @Override  
  61.         protected void onPostExecute(TypeUploadImage ui)  
  62.         {  
  63.             pd.dismiss();  
  64.         } 
posted @   郑文亮  阅读(5608)  评论(2编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示