Android开发之httpclient文件上传实现

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

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

时间: 2024-08-08 13:59:10

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

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

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

HttpClient文件上传下载

1 HTTP HTTP 协议可能是如今 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序须要直接通过 HTTP 协议来訪问网络资源. 尽管在 JDK 的 java.net 包中已经提供了訪问 HTTP 协议的基本功能,可是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活.HttpClient 用来提供高效的.最新的.功能丰富的支持 HTTP 协议的client编程工具包,而且它支持 HTTP 协议最新的版本号和建议. 一般的情况下我们都是使用Chro

httpclient 文件上传

/** * 上传文件 */ public static Boolean  uploadFile(String fileName, String url) { File file = new File(fileName); if (!file.exists()) { return false; } DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter( CoreProtocolPNam

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

随便写个方法 public function test2(){ $Weixin = new \Weixin\Controller\BaseController(); $this->assign('signPackage', $Weixin->jssdk->GetSignPackage()); $this->display(); } test2.html核心代码 <script type="text/javascript" src="__STATI

Android开发之R文件丢失

在进行android开发的过程中,不知道怎么回事,代码中出现R代码有红色波浪线了,于是进行了clean,结果还是有红色波浪线,然后就重启了eclipse,重启以后还是这个样子,随后发现工程的R文件丢失了.我擦....什么情况??? 然后google了一番,各种方法,现贴出来 1.选择eclipse/myeclipse 的 clean  这样R文件也会出现.  该方法不管用 2.对着工程点击鼠标右键 选择 Build Project,R.java 文件又回来    该方法不管用 3. 从别的工程中

Android网页WebView图片文件上传的问题

在安卓下,webview上传图片点击是没用的,需要自己写一下. 网上关于这个的很多,基本都是抄来抄去,没什么用的. 这个日期比较新,而且能用 http://blog.csdn.net/djcken/article/details/46379929#comments 就是自定义实现 WebChromeClient 然后重写  openFileChooser  方法,获取 ValueCallback<Uri> valueCallback 当然,要注意不同版本的区别.,但5.0+的项目,就不能用了.

android webview type=file文件上传,安卓端代码

http://stackoverflow.com/questions/5907369/file-upload-in-webview http://blog.csdn.net/longlingli/article/details/16946047 1 package com.example.cairh_sjkh_it; 2 3 4 import android.app.Activity; 5 import android.app.AlertDialog; 6 import android.app.

android使用HttpURLConnection实现带参数文件上传

文件上传是常见功能,然而android网上大多数的文件上传都使用httpclient,而且需要添加一个httpmine-jar,其实HttpURLConnection也可以实现文件上传,但是它在移动端有个弊端,就是不能上传大文件,所以这次说的方式,只能上传一些较小的文件. 文件上传,并且带上一些参数,这需要我们了解http请求的构造方式,也就是它的格式. HttpURLConnection需要我们自己构造请求头部,也就是我们要拼接出一个正确完整的请求. 下面来看一个典型的例子 POST /api

Android客户端多文件上传

在web开发中,多文件上传时是非常方便的,直接使用Http协议提交数据即可.格式如下: <FORM METHOD=POST ACTION="http://192.168.1.101:8083/upload/servlet/UploadServlet" enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT TYPE