文件上传可能是一个比較耗时的操作,假设为上传操作带上进度提示则能够更好的提高用户体验,最后效果例如以下图:

项目源代码:http://download.csdn.net/detail/shinay/4965230

这里仅仅贴出代码,可依据实际情况自行改动。

[java] view
plain
copy

  1. package com.lxb.uploadwithprogress.http;
  2. import java.io.File;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.methods.HttpPost;
  6. import org.apache.http.entity.mime.content.FileBody;
  7. import org.apache.http.impl.client.DefaultHttpClient;
  8. import org.apache.http.protocol.BasicHttpContext;
  9. import org.apache.http.protocol.HttpContext;
  10. import org.apache.http.util.EntityUtils;
  11. import android.app.ProgressDialog;
  12. import android.content.Context;
  13. import android.os.AsyncTask;
  14. import com.lxb.uploadwithprogress.http.CustomMultipartEntity.ProgressListener;
  15. public class HttpMultipartPost extends AsyncTask<String, Integer, String> {
  16. private Context context;
  17. private String filePath;
  18. private ProgressDialog pd;
  19. private long totalSize;
  20. public HttpMultipartPost(Context context, String filePath) {
  21. this.context = context;
  22. this.filePath = filePath;
  23. }
  24. @Override
  25. protected void onPreExecute() {
  26. pd = new ProgressDialog(context);
  27. pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  28. pd.setMessage("Uploading Picture...");
  29. pd.setCancelable(false);
  30. pd.show();
  31. }
  32. @Override
  33. protected String doInBackground(String... params) {
  34. String serverResponse = null;
  35. HttpClient httpClient = new DefaultHttpClient();
  36. HttpContext httpContext = new BasicHttpContext();
  37. HttpPost httpPost = new HttpPost("上传URL, 如:http://www.xx.com/upload.php");
  38. try {
  39. CustomMultipartEntity multipartContent = new CustomMultipartEntity(
  40. new ProgressListener() {
  41. @Override
  42. public void transferred(long num) {
  43. publishProgress((int) ((num / (float) totalSize) * 100));
  44. }
  45. });
  46. // We use FileBody to transfer an image
  47. multipartContent.addPart("data", new FileBody(new File(
  48. filePath)));
  49. totalSize = multipartContent.getContentLength();
  50. // Send it
  51. httpPost.setEntity(multipartContent);
  52. HttpResponse response = httpClient.execute(httpPost, httpContext);
  53. serverResponse = EntityUtils.toString(response.getEntity());
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. return serverResponse;
  58. }
  59. @Override
  60. protected void onProgressUpdate(Integer... progress) {
  61. pd.setProgress((int) (progress[0]));
  62. }
  63. @Override
  64. protected void onPostExecute(String result) {
  65. System.out.println("result: " + result);
  66. pd.dismiss();
  67. }
  68. @Override
  69. protected void onCancelled() {
  70. System.out.println("cancle");
  71. }
  72. }
[java] view
plain
copy

  1. package com.lxb.uploadwithprogress.http;
  2. import java.io.FilterOutputStream;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.nio.charset.Charset;
  6. import org.apache.http.entity.mime.HttpMultipartMode;
  7. import org.apache.http.entity.mime.MultipartEntity;
  8. public class CustomMultipartEntity extends MultipartEntity {
  9. private final ProgressListener listener;
  10. public CustomMultipartEntity(final ProgressListener listener) {
  11. super();
  12. this.listener = listener;
  13. }
  14. public CustomMultipartEntity(final HttpMultipartMode mode,
  15. final ProgressListener listener) {
  16. super(mode);
  17. this.listener = listener;
  18. }
  19. public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,
  20. final Charset charset, final ProgressListener listener) {
  21. super(mode, boundary, charset);
  22. this.listener = listener;
  23. }
  24. @Override
  25. public void writeTo(OutputStream outstream) throws IOException {
  26. super.writeTo(new CountingOutputStream(outstream, this.listener));
  27. }
  28. public static interface ProgressListener {
  29. void transferred(long num);
  30. }
  31. public static class CountingOutputStream extends FilterOutputStream {
  32. private final ProgressListener listener;
  33. private long transferred;
  34. public CountingOutputStream(final OutputStream out,
  35. final ProgressListener listener) {
  36. super(out);
  37. this.listener = listener;
  38. this.transferred = 0;
  39. }
  40. public void write(byte[] b, int off, int len) throws IOException {
  41. out.write(b, off, len);
  42. this.transferred += len;
  43. this.listener.transferred(this.transferred);
  44. }
  45. public void write(int b) throws IOException {
  46. out.write(b);
  47. this.transferred++;
  48. this.listener.transferred(this.transferred);
  49. }
  50. }
  51. }

上面为两个基本的类,以下放一个调用的Activity

[java] view
plain
copy

  1. package com.lxb.uploadwithprogress;
  2. import java.io.File;
  3. import com.lxb.uploadwithprogress.http.HttpMultipartPost;
  4. import android.app.Activity;
  5. import android.content.Context;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.view.View.OnClickListener;
  9. import android.widget.Button;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. public class MainActivity extends Activity implements OnClickListener {
  13. private Context context;
  14. private EditText et_filepath;
  15. private Button btn_upload;
  16. private Button btn_cancle;
  17. private HttpMultipartPost post;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. context = this;
  22. setContentView(R.layout.activity_main);
  23. et_filepath = (EditText) findViewById(R.id.et_filepath);
  24. btn_upload = (Button) findViewById(R.id.btn_upload);
  25. btn_cancle = (Button) findViewById(R.id.btn_cancle);
  26. btn_upload.setOnClickListener(this);
  27. btn_cancle.setOnClickListener(this);
  28. }
  29. @Override
  30. public void onClick(View v) {
  31. switch (v.getId()) {
  32. case R.id.btn_upload:
  33. String filePath = et_filepath.getText().toString();
  34. File file = new File(filePath);
  35. if (file.exists()) {
  36. post = new HttpMultipartPost(context, filePath);
  37. post.execute();
  38. } else {
  39. Toast.makeText(context, "file not exists", Toast.LENGTH_LONG).show();
  40. }
  41. break;
  42. case R.id.btn_cancle:
  43. if (post != null) {
  44. if (!post.isCancelled()) {
  45. post.cancel(true);
  46. }
  47. }
  48. break;
  49. }
  50. }
  51. }

当然,在Android中使用MultipartEntity类,必须为项目添加对应的jar包,httpmime-4.1.2.jar。

最后放上代码。project里已包括jar。

地址:

http://download.csdn.net/detail/shinay/4965230

最新文章

  1. 【Effective Java】7、优先考虑泛型方法
  2. C++调用C中编译过的函数要加extern &quot;C&quot;
  3. CodeForces 711D Directed Roads (DFS判环+计数)
  4. SQL server 2012序列号 注册码 z
  5. iOS afnetworking最新版报错 没有AFHTTPRequestOperationManager类了
  6. pygame初步(一)绘制一个运动的矩形
  7. 130825组队赛-Regionals 2012, North America - East Central NA
  8. ECMAScript 6 笔记(四)
  9. jemter测试中常见的名词解析
  10. Python是如何实现生成器的原理
  11. Springboot框架,实现请求数据解密,响应数据加密的功能。
  12. MyEclipse和tomcat结合编写jsp对于中文乱码的解决方法
  13. Win10系列:VC++ Direct3D模板介绍3
  14. 【系统架构】亿级Web系统搭建(1):Web负载均衡
  15. 2018 Multi-University Training Contest 5
  16. Mac terminal Javac
  17. bzoj3709: [PA2014]Bohater(贪心)
  18. 【CodeForces】576 C. Points on Plane
  19. Socket_FTP
  20. webstorm打开带有node_modules文件夹的工程时很卡

热门文章

  1. C#的Convert.FromBase64String
  2. Python的程序结构[7] -&gt; 生成器/Generator -&gt; 生成器浅析
  3. 【排序】逆序对IV
  4. Flip Game -- LeetCode
  5. Filter过滤器笔记1
  6. iOS_字典数组 按key分组和排序
  7. 利用.net4.0的dynamic特性制造的超级简单的微信SDK
  8. Android - toolbar navigation 样式
  9. windows下搭建svn服务器
  10. Windows下cwRsyncServer双机连续同步部署