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

http://www.cnblogs.com/perfy/p/3783915.html

 

使用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/