1. package com.home.uploadfile;
  2.  
  3. import java.io.File;
  4.  
  5. import android.app.Activity;
  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.Toast;
  11.  
  12. public class MainActivity extends Activity implements OnClickListener {
  13.  
  14. private Button uploadBtn;
  15. private HttpMultipartPost post;
  16.  
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.main);
  21. uploadBtn = (Button) findViewById(R.id.main_btn_upload);
  22. uploadBtn.setOnClickListener(this);
  23. }
  24.  
  25. @Override
  26. public void onClick(View v) {
  27. if (v == uploadBtn) {
  28. // 自己手机上的一张图片路径
  29. String filePath = "/storage/sdcard0/updateAdtech/orgpic/1.png";
  30. String url = "http://service.ireadhome.com/api/Upload/Image";
  31. File file = new File(filePath);
  32. if (file.exists()) {
  33. post = new HttpMultipartPost(MainActivity.this, filePath, url);
  34. post.execute();
  35. } else {
  36. Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_LONG)
  37. .show();
  38. }
  39. }
  40. // if (post != null) {
  41. // if (!post.isCancelled()) {
  42. // post.cancel(true);
  43. // }
  44. // }
  45. }
  46. }

  AsyncTask子类:HttpMultipartPost:

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

  MultipartEntity子类:CustomMultipartEntity

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

  参考:

http://m.blog.csdn.net/blog/u010142437/14639651

http://toolongdidntread.com/android/android-multipart-post-with-progress-bar/

使用MultipartEntity上传文件(带进度对话框)的更多相关文章

  1. Extjs 使用fileupload插件上传文件 带进度条显示

    一.首先我们看看官方给出的插件的解释: 一个文件上传表单项具有自定义的样式,并且可以控制按钮的文本和 像文本表单的空文本类似的其他特性. 它使用一个隐藏的文件输入元素,并在用户选择文件后 在form提 ...

  2. asp.net mvc 实现上传文件带进度条

    本文乃是博主早期写的,此种思路虽然实现了,但固然不是最好的,仅做参考学习. 可以用js onprogress .fileinput .webuploader.jq ajaxsubmit等实现 思路:a ...

  3. FormData上传文件 带进度条

    * jQuery ajax  FormData 上传文件 template $.ajax({ url: url, type: 'POST', data: new FormData(form), dat ...

  4. ASP.NET Jquery+ajax上传文件(带进度条)

    效果图 支持ie6+,chrome,ie6中文文件名会显示乱码. 上传时候会显示进度条. 需要jquery.uploadify.js插件,稍后会给出下载 前台代码 <%@ Page Langua ...

  5. jquery ajax php 无刷新上传文件 带 遮罩 进度条 效果的哟

    在很多项目中都会叫用户上传东西这些的,自从接触了jquery 和ajax之后就不管做什么,首先都会想到这个,我这个人呢?是比较重视客户体验的,这次我这边负责的是后台板块,然后就有一块是要求用户上传照片 ...

  6. java进行文件上传,带进度条

    网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码 项目环境:jkd7.tomcat7. jar包:commons-fileupload-1.2.1.jar.commons-io-1 ...

  7. ajax上传文件显示进度

    下面要做一个ajax上传文件显示进度的操作,文末有演示地址 这里先上代码: 1.前端代码 upload.html <!DOCTYPE html> <html lang="e ...

  8. js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中

    ajaxfileupload.js jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId ...

  9. 【Web】前端文件上传,带进度条

    最近做项目发现,在文件上传的过程中,增加进度条,能大大改善用户体验.本例介绍带进度条的文件上传 环境搭建 参考:[Java]JavaWeb文件上传和下载. 原生ajax上传带进度条 <%@ pa ...

  10. servlet多文件上传(带进度条)

    需要commons-fileupload-1.3.jar和commons-io-2.4.jar的支持 页面效果:(图片文件都可以) (1)进度标识类 public class UploadStatus ...

随机推荐

  1. 【js】sort()

    //为了实现排序,sort()方法会调用每个数组项的toString()转型方法,然后比较得到的字符串, //以确定如何排序.即使数组中的每一项都是数值,sort()方法比较的也是字符串, var v ...

  2. 转 selenium 自动下载文件

    #coding=utf-8from selenium import webdriver #实例化一个火狐配置文件fp = webdriver.FirefoxProfile() #设置各项参数,参数可以 ...

  3. 转 虫师的selenium借助AutoIt识别上传(下载)详解

    selenium借助AutoIt识别上传(下载)详解 2014-12-27 11:26 by 虫师, 755 阅读, 1 评论, 收藏,  编辑 AutoIt目前最新是v3版本,这是一个使用类似BAS ...

  4. PLSQL_Oracle基本概念总结(汇总)

    2014-08-16 Created By BaoXinjian

  5. android检测网络连接状态示例讲解

    网络的时候,并不是每次都能连接到网络,因此在程序启动中需要对网络的状态进行判断,如果没有网络则提醒用户进行设置   Android连接首先,要判断网络状态,需要有相应的权限,下面为权限代码(Andro ...

  6. Linux时间子系统(十六) clockevent

    一.clock event控制的通用逻辑 1.产生clock event的设备 各种系统的timer硬件形形色色,不过在general clock event device layer,struct ...

  7. hibernate,动态更新,插入 dynamic-insert,dynamic-update 我有话要说 ---稍后整理

    http://dreamzhong.iteye.com/blog/1207377 http://blog.csdn.net/hsuxu/article/details/8108326 @org.hib ...

  8. LaTeX 编辑软件WinEdt使用简要介绍

    LaTeX 编辑软件WinEdt使用简要介绍   LaTeX 的起源非常牛逼,有一套书大家可能听说过<计算机程序设计艺术>,写了好几本.当然能在计算机方面写上艺术俩字的书恐怕不是我们一般人 ...

  9. spring cloud中通过配置文件自定义Ribbon负载均衡策略

    一.Ribbon中的负载均衡策略 1.Ribbon中支持的负载均衡策略 AvailabilityFilteringRule:过滤掉那些因为一直连接失败的被标记为circuit tripped的后端se ...

  10. VS2008配置OpenGl 亲测可行

    OpenGL作为当前主流的图形API之一,它在一些场合具有比DirectX更优越的特性.1.与C语言紧密结合.OpenGL命令最初就是用C语言函数来进行描述的,对于学习过C语言的人来讲,OpenGL是 ...