使用MultipartEntity上传文件(带进度对话框)

+ ?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

package
com.home.uploadfile;

import java.io.File;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import
android.widget.Toast;

public
class MainActivity extends
Activity implements
OnClickListener {

    private
Button uploadBtn;

    private
HttpMultipartPost post;

    @Override

    protected
void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        uploadBtn = (Button) findViewById(R.id.main_btn_upload);

        uploadBtn.setOnClickListener(this);

    }

    @Override

    public
void onClick(View v) {

        if
(v == uploadBtn) {

            // 自己手机上的一张图片路径

            String filePath = "/storage/sdcard0/updateAdtech/orgpic/1.png";

            String url = "http://service.ireadhome.com/api/Upload/Image";

            File file = new
File(filePath);

            if
(file.exists()) {

                post = new
HttpMultipartPost(MainActivity.this, filePath, url);

                post.execute();

            } else
{

                Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_LONG)

                        .show();

            }

        }

        // if (post != null) {

        // if (!post.isCancelled()) {

        // post.cancel(true);

        // }

        // }

    }

}

  AsyncTask子类:HttpMultipartPost:

+ ?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

package
com.home.uploadfile;

import java.io.File;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.impl.client.DefaultHttpClient;

import
org.apache.http.protocol.BasicHttpContext;

import
org.apache.http.protocol.HttpContext;

import
org.apache.http.util.EntityUtils;

import
com.home.uploadfile.CustomMultipartEntity.ProgressListener;

import
android.app.ProgressDialog;

import
android.content.Context;

import
android.os.AsyncTask;

public
class HttpMultipartPost extends
AsyncTask<String, Integer, String> {

    private
Context context;

    private
String filePath;

    private
ProgressDialog pd;

    private
long totalSize;

    private
String requestUrl;

    public
HttpMultipartPost(Context context, String filePath, String requestUrl) {

        this.context = context;

        this.filePath = filePath;

        this.requestUrl = requestUrl;

    }

    @Override

    protected
void onPreExecute() {

        pd = new
ProgressDialog(context);

        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        pd.setMessage("Uploading Picture...");

        pd.setCancelable(false);

        pd.show();

    }

    @Override

    protected
String doInBackground(String... params) {

        String serverResponse = null;

        HttpClient httpClient = new
DefaultHttpClient();

        HttpContext httpContext = new
BasicHttpContext();

        HttpPost httpPost = new
HttpPost(requestUrl);

        try
{

            CustomMultipartEntity multipartContent = new
CustomMultipartEntity(

                    new
ProgressListener() {

                        @Override

                        public
void transferred(long
num) {

                            publishProgress((int) ((num / (float) totalSize) * 100));

                        }

                    });

            // 使用FileBody上传图片

            multipartContent.addPart("value", new
FileBody(new
File(filePath)));

            totalSize = multipartContent.getContentLength();

            // 上传

            httpPost.setEntity(multipartContent);

            HttpResponse response = httpClient.execute(httpPost, httpContext);

            serverResponse = EntityUtils.toString(response.getEntity());

            System.out.println(serverResponse);

        } catch
(Exception e) {

            e.printStackTrace();

        }

        return
serverResponse;

    }

    @Override

    protected
void onProgressUpdate(Integer... progress) {

        pd.setProgress((int) (progress[0]));

    }

    @Override

    protected
void onPostExecute(String result) {

        System.out.println("result: "
+ result);

        pd.dismiss();

    }

    @Override

    protected
void onCancelled() {

        System.out.println("cancle");

    }

}

  MultipartEntity子类:CustomMultipartEntity

+ ?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

package
com.home.uploadfile;

import java.io.FilterOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;

import org.apache.http.entity.mime.MultipartEntity;

public
class CustomMultipartEntity extends
MultipartEntity {

    private
final ProgressListener listener;

    public
CustomMultipartEntity(final
ProgressListener listener) {

        super();

        this.listener = listener;

    }

    public
CustomMultipartEntity(final
HttpMultipartMode mode,

            final
ProgressListener listener) {

        super(mode);

        this.listener = listener;

    }

    public
CustomMultipartEntity(HttpMultipartMode mode, final
String boundary,

            final
Charset charset, final
ProgressListener listener) {

        super(mode, boundary, charset);

        this.listener = listener;

    }

    @Override

    public
void writeTo(OutputStream outstream) throws
IOException {

        super.writeTo(new
CountingOutputStream(outstream, this.listener));

    }

    public
static interface ProgressListener {

        void
transferred(long
num);

    }

    public
static class CountingOutputStream extends
FilterOutputStream {

        private
final ProgressListener listener;

        private
long transferred;

        public
CountingOutputStream(final
OutputStream out,

                final
ProgressListener listener) {

            super(out);

            this.listener = listener;

            this.transferred = 0;

        }

        public
void write(byte[] b, int
off, int
len) throws
IOException {

            out.write(b, off, len);

            this.transferred += len;

            this.listener.transferred(this.transferred);

        }

        public
void write(int
b) throws
IOException {

            out.write(b);

            this.transferred++;

            this.listener.transferred(this.transferred);

        }

    }

}

  参考:

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

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

时间: 2024-10-26 02:38:52

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

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

一.首先我们看看官方给出的插件的解释: 一个文件上传表单项具有自定义的样式,并且可以控制按钮的文本和 像文本表单的空文本类似的其他特性. 它使用一个隐藏的文件输入元素,并在用户选择文件后 在form提交的同时执行实际的文件上传. 因为没有安全的跨浏览器以编程的方式对file表单项设值的方式, 所以标准表单项的 setValue 方法是无效的. getvalue方法的返回值取决于使用何种浏览器; 一些仅仅返回文件名, 一些返回一个完整的文件路径, 一些则返回文件的虚拟路径. 二.在我看来这个插件就

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

思路:ajax异步上传文件,且开始上传文件的时候启动轮询来实时获取文件上传进度.保存进度我采用的是memcached缓存,因为项目其他地方也用了的,所以就直接用这个啦.注意:不能使用session来保存进度,因为session是线程安全的不能实时获取进度,可是试试httpcache或者memorycache,这两个我没有试过,请自行尝试. ps:使用websocket来实现也是不错的,不过我没有试过,有心的大神可以去试试. 下面贴一张效果图: 前端ajax上传文件,我使用了两种jq插件.一种是a

ajax上传文件带进度条的思路

首先,需要2个重要的数据,total(文件总大小)和loaded(已经上传的大小),用 loaded/total,然后不断的更新进度条即可: 问:怎么拿到这两个重要数据呢? 答:在html5中有一个上传过程事件onprogress,在这个事件中可以读到这两个数据loaded和total:上传的时候不断的触发这个函数,然后更新进度条即可: 1 xhr.upload.onprogress = function(ev){ 2 if(ev.lengthComputable){ 3 //有可能文件时分块上

asp.net 文件批量选取,批量上传,带进度条,uploadify3.2 TOP

http://www.16aspx.com/Article/3444 asp.net 文件批量选取,批量上传,带进度条,uploadify3.2 TOP,布布扣,bubuko.com

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

ajaxfileupload.js jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '&qu

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

需要commons-fileupload-1.3.jar和commons-io-2.4.jar的支持 页面效果:(图片文件都可以) (1)进度标识类 public class UploadStatus { private long bytesRead; private long contentLength; private int items; private long startTime = System.currentTimeMillis(); //set get 方法 省略 } (2)监听

不带插件 ,自己写js,实现批量上传文件及进度显示

今天接受项目中要完成文件批量上传文件而且还要显示上传进度,一开始觉得这个应该不是很麻烦,当我在做的时候遇到了很多问题,很头疼啊. 不过看了别人写的代码,自己也测试过,发现网上好多都存在一些问题,并不是自己想要的.然后自己查阅各种资料,经过自己总结,最终完成了这个功能. 如果大家有什么问题可以提出来,一起交流,学习.有什么不对的地方也指出来,我也虚心学习.自己也是刚写博客,您们的赞是我写博客的动力,谢谢大家. 条件:我采用struts2,java ,ajax,FormData实现; 1.实现的逻辑

EXTJS+ASP.NET上传文件带实时进度条代码

一,文件夹 二,upLoad.cs是继承IHttpModule的类: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.IO; using System.Reflection; using System.Globalization; using System.Web.Hosting; /// <summary>

jQuery上传文件显示进度条

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="../js/jquery.js"></script> </head> <body> <h2>HTML5异步上传文件,带进度条(jQuery)</h2> <form method="post"

XMLHttpRequest上传文件实现进度条

话不多说,直接上代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>XMLHttpRequest上传文件进度实现</title> <script type="text/javascript"> var xhr; var ot;// var oloaded; //上传文件方法 function UpladFil