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
- 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);
- }
- }
- }
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
- class HttpMultipartPost extends AsyncTask<HttpResponse, Integer, TypeUploadImage>
- {
- ProgressDialog pd;
- long totalSize;
- @Override
- protected void onPreExecute()
- {
- pd = new ProgressDialog(this);
- pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- pd.setMessage("Uploading Picture...");
- pd.setCancelable(false);
- pd.show();
- }
- @Override
- protected TypeUploadImage doInBackground(HttpResponse... arg0)
- {
- HttpClient httpClient = new DefaultHttpClient();
- HttpContext httpContext = new BasicHttpContext();
- HttpPost httpPost = new HttpPost("http://herpderp.com/UploadImage.php");
- try
- {
- CustomMultipartEntity multipartContent = new CustomMultipartEntity(new ProgressListener()
- {
- @Override
- public void transferred(long num)
- {
- publishProgress((int) ((num / (float) totalSize) * 100));
- }
- });
- // We use FileBody to transfer an image
- multipartContent.addPart("uploaded_file", new FileBody(new File(m_userSelectedImagePath)));
- totalSize = multipartContent.getContentLength();
- // Send it
- httpPost.setEntity(multipartContent);
- HttpResponse response = httpClient.execute(httpPost, httpContext);
- String serverResponse = EntityUtils.toString(response.getEntity());
- ResponseFactory rp = new ResponseFactory(serverResponse);
- return (TypeImage) rp.getData();
- }
- catch (Exception e)
- {
- System.out.println(e);
- }
- return null;
- }
- @Override
- protected void onProgressUpdate(Integer... progress)
- {
- pd.setProgress((int) (progress[0]));
- }
- @Override
- protected void onPostExecute(TypeUploadImage ui)
- {
- pd.dismiss();
- }
分类:
手机开发(Android)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 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】