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

项目源代码: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. centos7部署nagios

    一.Nagios简介 Nagios是一款开源的电脑系统和网络监视工具,能有效监控Windows.Linux和Unix的主机状态,交换机路由器等网络设置,打印机等.在系统或服务状态异常时发出邮件或短信报 ...

  2. Weblogic 监控工具汇总及简介

    https://blog.csdn.net/hualusiyu/article/details/39608637

  3. Netty源码学习(六)ChannelPipeline

    0. ChannelPipeline简介 ChannelPipeline = Channel + Pipeline,也就是说首先它与Channel绑定,然后它是起到类似于管道的作用:字节流在Chann ...

  4. Extract - <<凤凰牌老熊-现代支付系统设计>>

    本文摘录自: http://blog.lixf.cn/essay/2017/04/01/concept-01-overview/ 一.支付概述-- 1. 支付与交易 交易过程: 交易的存在是支付发生的 ...

  5. bzoj 3462: DZY Loves Math II

    3462: DZY Loves Math II Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 211  Solved: 103[Submit][Sta ...

  6. Bluetooth篇 开发实例之五 为什么无线信号(RSSI)是负值?

    原文:http://www.cnblogs.com/lele/articles/2832885.html   为什么无线信号(RSSI)是负值 答:其实归根到底为什么接收的无线信号是负值,这样子是不是 ...

  7. PHP switch的“高级”用法详解

    只所以称为“高级”用法,是因为我连switch的最基础的用法都还没有掌握,so,接下来讲的其实还是它的基础用法! switch 语句和具有同样表达式的一系列的 IF 语句相似.很多场合下需要把同一个变 ...

  8. IOS设置UIView的边框为圆角

    iOS 系统自带的 View 组件都是正方形的,看起来都太生硬,有时候我需要变成圆角形式,如下图:    具体的实现是使用QuartzCore库,下面我具体的描述一下实现过程:    •    首先 ...

  9. win2008 安装 配置 mysql

    安装的是windows Server 2008 R2 操作系统  按照国际管理,安装了数据库 MYSQL 5.0.    一路顺利,可以通过外部连接MYSQL的时候出现了问题,无论如何也连接不上  发 ...

  10. Spring整合Hibernate的时候使用hibernate.cfg.xml

    Spring整合Hibernate其实也就是把Hibernate的SessionFactory对象封装成:org.springframework.orm.hibernate3.LocalSession ...