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

项目源代码: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

Android开发之httpclient文件上传实现的更多相关文章

  1. [置顶] Android开发之XML文件的解析

    Android系统开发之XML文件的解析 我们知道Http在网络传输中的数据组织方式有三种分别为:XML方式.HTML方式.JSON方式.其中XML为可扩展标记语言,如下: <?xml vers ...

  2. springMVC + hadoop + httpclient 文件上传请求直接写入hdfs

    1.首先是一个基于httpclient的java 应用程序,代码在这篇文章的开头:点击打开链接 2.我们首先写一个基于springMVC框架的简单接收请求上传的文件保存本地文件系统的demo,程序代码 ...

  3. Android Retrofit 2.0文件上传

    Android Retrofit 实现(图文上传)文字(参数)和多张图片一起上传 使用Retrofit进行文件上传,肯定离不开Part & PartMap. public interface ...

  4. HttpClient文件上传下载

    1 HTTP HTTP 协议可能是如今 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序须要直接通过 HTTP 协议来訪问网络资源. 尽管在 JDK 的 java.net ...

  5. Android采取async框架文件上传

    页面效果 须要的权限 <uses-permission android:name="android.permission.INTERNET"/> 网络訪问权限; 布局文 ...

  6. httpclient 文件上传

    /**      * 上传文件      */     public static Boolean  uploadFile(String fileName, String url) {         ...

  7. thinkphp微信开发之jssdk图片上传并下载到本地服务器

    public function test2(){ $Weixin = new \Weixin\Controller\BaseController(); $this->assign('signPa ...

  8. android 使用Retrofit2 RxJava 文件上传

    private static void upload(final Context context, final int type, File logFile) { Map<String, Req ...

  9. Android开发之SD卡上文件操作

    1. 得到存储设备的目录:/SDCARD(一般情况下) SDPATH=Environment.getExternalStorageDirectory()+"/"; 2. 判断SD卡 ...

随机推荐

  1. windows编程中的数据类型

    在windows编程中,有许多奇怪的数据类型,初学者不知道这些代表什么,下面就把一些数据类型列出如下: ATOM 原子(原子表中的一个字符串的参考) BOOL 布尔变量 BOOLEAN 布尔变量 BY ...

  2. spring JPA写法一种

    第一次用,搞了半天,终于知道了大概. 基于ORM的JPA还是蛮好用的, 这次是实现一个MANGODB的日志存储和检索. PRISM用的. repository的写法: package paic.sto ...

  3. J.U.C并发框架源码阅读(十七)ReentrantReadWriteLock

    基于版本jdk1.7.0_80 java.util.concurrent.locks.ReentrantReadWriteLock 代码如下 /* * ORACLE PROPRIETARY/CONFI ...

  4. 元素类型 “meta” 必须由匹配的结束标记 “” 终止

    报错 org.xml.sax.SAXParseException: 元素类型 “meta” 必须由匹配的结束标记 “” 终止 系统自动创建 <meta charset="UTF-8&q ...

  5. android新创建一个Activity时,会创建哪些部分

    在创建时,会提示创建部分. 详细部分:

  6. 国内 docker 仓库镜像对比

    http://www.datastart.cn/tech/2016/09/28/docker-mirror.html

  7. pr_debug、dev_dbg等动态调试三

    内核版本:Linux-3.14 作者:彭东林 邮箱:pengdonglin137@163.com 如果没有使用CONFIG_DYNAMIC_DEBUG,那么就需要定义DEBUG,那么此时pr_debu ...

  8. IT开发者对Mac钟爱

    由于Mac的操作系统OSX相比Windows win7/8/10来说,比較适合开发者使用.个人的体会例如以下: 首先.OSX的多窗体多应用程序切换功能非常强大,对开发者来说非常实用.开发者一般都须要开 ...

  9. bash: /bin/bash^M: bad interpreter: No such file or directory

    在windows下编写shell脚本在linux下运行会出报错: [hadoop@master data]$ ./load_ods_table.sh -bash: ./load_ods_table.s ...

  10. SparkMLlib基础内容

    SparkMLlib基础内容 (一),多种数据类型 1.1 本地向量集 def testVetor: Unit ={ val vd:Vector=Vectors.dense(2,3,6) printl ...