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

项目源代码: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. 关于多态的理解,有助于理解TStream抽象类的多态机制。

    有的时候 不是很明白流的机制,因为有内存流  文件流 图片流 等等 他们之间的相互转化 靠的就是流的多态性.... unit Unit11; interface uses Winapi.Windows ...

  2. mysql故障(主从复制sql线程不运行)

    故障现象: 进入slave服务器,运行: mysql> show slave status\G ....... Relay_Log_File: localhost Relay_Log_Pos: ...

  3. Ionic 存储目录 CORS

    使用不同的存储库结构官方为 { "scripts": { "install": "cd path-to/your-app && npm ...

  4. 在MSSQL中将数字转换成中文

    具体代码如下: CREATE FUNCTION [dbo].[fn_NumberToChinese] (@number INT) ) AS BEGIN ); ); ); SET @res = ''; ...

  5. (1)C# 创建ef sqlserver

    连接sql 如果报错不能连接的错误 把这三个IP地址的端口号设置上,并启用.第一个18.6是本机ip,之后就可以测试了 最后重启服务器

  6. Python的Web编程[1] -> Web服务器[0] -> Web 服务器与 CGI / WSGI

    Web服务器 / Web Server 对于Web来说,需要建立一个Web服务器,必须建立一个基本的服务器和一个处理程序, 基本服务器的主要作用是,在客户端和服务器端完成必要的HTTP交互, 处理程序 ...

  7. spark-join算子

  8. POJ 2104 K-th Number (划分树)

                                                                K-th Number Time Limit: 20000MS   Memory ...

  9. 使用GEANT4的模拟技术1

    简介 本文来源于意大利国家核物理研究院INFN的08年的slides.原文名称simulation techniques using geant4,原文主要讲述的是开发geant4用户程序的方法.这里 ...

  10. MS SQL数据批量备份还原(适用于MS SQL 2005+)

    原文:MS SQL数据批量备份还原(适用于MS SQL 2005+) 我们知道通过Sql代理,可以实现数据库的定时备份功能:当数据库里的数据库很多时,备份一个数据库需要建立对应的定时作业,相对来说比较 ...