Android开发之httpclient文件上传实现
文件上传可能是一个比較耗时的操作,假设为上传操作带上进度提示则能够更好的提高用户体验,最后效果例如以下图:
项目源代码:http://download.csdn.net/detail/shinay/4965230
这里仅仅贴出代码,可依据实际情况自行改动。
- package com.lxb.uploadwithprogress.http;
- 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 android.app.ProgressDialog;
- import android.content.Context;
- import android.os.AsyncTask;
- import com.lxb.uploadwithprogress.http.CustomMultipartEntity.ProgressListener;
- public class HttpMultipartPost extends AsyncTask<String, Integer, String> {
- private Context context;
- private String filePath;
- private ProgressDialog pd;
- private long totalSize;
- public HttpMultipartPost(Context context, String filePath) {
- this.context = context;
- this.filePath = filePath;
- }
- @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("上传URL, 如:http://www.xx.com/upload.php");
- try {
- CustomMultipartEntity multipartContent = new CustomMultipartEntity(
- new ProgressListener() {
- @Override
- public void transferred(long num) {
- publishProgress((int) ((num / (float) totalSize) * 100));
- }
- });
- // We use FileBody to transfer an image
- multipartContent.addPart("data", new FileBody(new File(
- filePath)));
- totalSize = multipartContent.getContentLength();
- // Send it
- httpPost.setEntity(multipartContent);
- HttpResponse response = httpClient.execute(httpPost, httpContext);
- serverResponse = EntityUtils.toString(response.getEntity());
- } 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");
- }
- }
- package com.lxb.uploadwithprogress.http;
- 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);
- }
- }
- }
上面为两个基本的类,以下放一个调用的Activity
- package com.lxb.uploadwithprogress;
- import java.io.File;
- import com.lxb.uploadwithprogress.http.HttpMultipartPost;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class MainActivity extends Activity implements OnClickListener {
- private Context context;
- private EditText et_filepath;
- private Button btn_upload;
- private Button btn_cancle;
- private HttpMultipartPost post;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- context = this;
- setContentView(R.layout.activity_main);
- et_filepath = (EditText) findViewById(R.id.et_filepath);
- btn_upload = (Button) findViewById(R.id.btn_upload);
- btn_cancle = (Button) findViewById(R.id.btn_cancle);
- btn_upload.setOnClickListener(this);
- btn_cancle.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.btn_upload:
- String filePath = et_filepath.getText().toString();
- File file = new File(filePath);
- if (file.exists()) {
- post = new HttpMultipartPost(context, filePath);
- post.execute();
- } else {
- Toast.makeText(context, "file not exists", Toast.LENGTH_LONG).show();
- }
- break;
- case R.id.btn_cancle:
- if (post != null) {
- if (!post.isCancelled()) {
- post.cancel(true);
- }
- }
- break;
- }
- }
- }
当然,在Android中使用MultipartEntity类,必须为项目添加对应的jar包,httpmime-4.1.2.jar。
最后放上代码。project里已包括jar。
地址:
Android开发之httpclient文件上传实现的更多相关文章
- [置顶] Android开发之XML文件的解析
Android系统开发之XML文件的解析 我们知道Http在网络传输中的数据组织方式有三种分别为:XML方式.HTML方式.JSON方式.其中XML为可扩展标记语言,如下: <?xml vers ...
- springMVC + hadoop + httpclient 文件上传请求直接写入hdfs
1.首先是一个基于httpclient的java 应用程序,代码在这篇文章的开头:点击打开链接 2.我们首先写一个基于springMVC框架的简单接收请求上传的文件保存本地文件系统的demo,程序代码 ...
- Android Retrofit 2.0文件上传
Android Retrofit 实现(图文上传)文字(参数)和多张图片一起上传 使用Retrofit进行文件上传,肯定离不开Part & PartMap. public interface ...
- HttpClient文件上传下载
1 HTTP HTTP 协议可能是如今 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序须要直接通过 HTTP 协议来訪问网络资源. 尽管在 JDK 的 java.net ...
- Android采取async框架文件上传
页面效果 须要的权限 <uses-permission android:name="android.permission.INTERNET"/> 网络訪问权限; 布局文 ...
- httpclient 文件上传
/** * 上传文件 */ public static Boolean uploadFile(String fileName, String url) { ...
- thinkphp微信开发之jssdk图片上传并下载到本地服务器
public function test2(){ $Weixin = new \Weixin\Controller\BaseController(); $this->assign('signPa ...
- android 使用Retrofit2 RxJava 文件上传
private static void upload(final Context context, final int type, File logFile) { Map<String, Req ...
- Android开发之SD卡上文件操作
1. 得到存储设备的目录:/SDCARD(一般情况下) SDPATH=Environment.getExternalStorageDirectory()+"/"; 2. 判断SD卡 ...
随机推荐
- 微信小程序实现豆瓣读书
个人练习项目,使用了scss+webstorm watcher来处理样式.整体上没有什么难点. github:https://github.com/axel10/wx-douban-read
- Southern African 2001 框架折叠 (拓扑序列的应用)
本文链接:http://www.cnblogs.com/Ash-ly/p/5398377.html 题目:考虑五个图片堆叠在一起,比如下面的9 * 8 的矩阵表示的是这些图片的边缘框. 现在上面的图片 ...
- [Python Cookbook] Pandas: Indexing of DataFrame
Selecting a Row df.loc[index] # if index is a string, add ' '; if index is a number, no ' ' or df.il ...
- 洛谷 U19159 采摘毒瘤
题目背景 Salamander见到路边有如此多的毒瘤,于是见猎心喜,从家里拿来了一个大袋子,准备将一些毒瘤带回家. 题目描述 路边共有nn 种不同的毒瘤,第i 种毒瘤有k_i 个,每个需要占据d_i ...
- Shader与AGAL(From 7yue)
- 【NOIP模拟赛】【乱搞AC】【贪心】【模拟】匹配
匹配 (match.pas/match.c/match.cpp) [题目描述] 到了新的学期,Mcx痛苦的发现通用技术课居然是有实验课的,这样的话他就不得不放弃写作业的想法而去做一件类似于搭积木的事情 ...
- APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate notice, with the fields e ...
- MySQL时间增加、字符串拼接
MySQL时间增加.字符串拼接 SELECT DATE_ADD(startTime, INTERVAL 10 SECOND); CONCAT(string1,string2,…)
- 基于Storyboard的创建多分支NavigationController的方法
如果遇到本文图片只展示一半的情况,多数情况下刷新一下浏览器即可 遇到的问题 我在写程序的时候碰到这样一个简单的需求,用户点击"我的XX"这样的功能时候,需要判断当前用户是否已经登录 ...
- C#控件之DataGridView
第一种:DataSet ds=new DataSet (); this.dataGridView1.DataSource=ds.Table[0]; 第二种:DataTable dt=new DataT ...