使用MultipartEntity上传文件(带进度对话框)
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:
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
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/
使用MultipartEntity上传文件(带进度对话框)的更多相关文章
- Extjs 使用fileupload插件上传文件 带进度条显示
一.首先我们看看官方给出的插件的解释: 一个文件上传表单项具有自定义的样式,并且可以控制按钮的文本和 像文本表单的空文本类似的其他特性. 它使用一个隐藏的文件输入元素,并在用户选择文件后 在form提 ...
- asp.net mvc 实现上传文件带进度条
本文乃是博主早期写的,此种思路虽然实现了,但固然不是最好的,仅做参考学习. 可以用js onprogress .fileinput .webuploader.jq ajaxsubmit等实现 思路:a ...
- FormData上传文件 带进度条
* jQuery ajax FormData 上传文件 template $.ajax({ url: url, type: 'POST', data: new FormData(form), dat ...
- ASP.NET Jquery+ajax上传文件(带进度条)
效果图 支持ie6+,chrome,ie6中文文件名会显示乱码. 上传时候会显示进度条. 需要jquery.uploadify.js插件,稍后会给出下载 前台代码 <%@ Page Langua ...
- jquery ajax php 无刷新上传文件 带 遮罩 进度条 效果的哟
在很多项目中都会叫用户上传东西这些的,自从接触了jquery 和ajax之后就不管做什么,首先都会想到这个,我这个人呢?是比较重视客户体验的,这次我这边负责的是后台板块,然后就有一块是要求用户上传照片 ...
- java进行文件上传,带进度条
网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码 项目环境:jkd7.tomcat7. jar包:commons-fileupload-1.2.1.jar.commons-io-1 ...
- ajax上传文件显示进度
下面要做一个ajax上传文件显示进度的操作,文末有演示地址 这里先上代码: 1.前端代码 upload.html <!DOCTYPE html> <html lang="e ...
- js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中
ajaxfileupload.js jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId ...
- 【Web】前端文件上传,带进度条
最近做项目发现,在文件上传的过程中,增加进度条,能大大改善用户体验.本例介绍带进度条的文件上传 环境搭建 参考:[Java]JavaWeb文件上传和下载. 原生ajax上传带进度条 <%@ pa ...
- servlet多文件上传(带进度条)
需要commons-fileupload-1.3.jar和commons-io-2.4.jar的支持 页面效果:(图片文件都可以) (1)进度标识类 public class UploadStatus ...
随机推荐
- spring 4.0下集成webservice
该教程使用的项目可参见: Intellij Idea下搭建基于Spring+SpringMvc+MyBatis的WebApi接口架构 具体源码请参见GitHub: https://github.com ...
- RHEL6 - 图形化设置IP
RHEL6下我们除了麻烦地修改网卡的主配置文件外,还可以通过setup,system-config-network等工具指令打开网卡的图形化界面 #setup #system-config-net ...
- 在Debug模式下中断, 在Release模式下跳出当前函数的断言
在Debug模式下中断, 在Release模式下跳出当前函数的断言 #ifdef DEBUG #define __breakPoint_on_debug asm("int3") # ...
- mysql 添加列的索引
无论哪种模式加入索引.会大幅度增加SELECT速度 索引名:Index_User_Name 栏目名:user_name 索引类型:Nornal 索引方式:BTREE
- unity update与fixedUpdate
update与渲染同步.fixedUpdate与物理同步. 在update中,speed要乘以Time.deltaTime.在fixedUpdate中,speed要乘以Time.fixedDeltaT ...
- tcp connection
三次握手与四次挥手的原因 https://yq.aliyun.com/articles/7435?spm=5176.8091938.0.0.N4v33a linux里的backlog详解 tcp co ...
- Maven 在eclipse中如何配置
大部分码农们都很熟悉Eclipse,用eclipse开发项目,Maven是解决依赖库的一个非常好用的java工具,可以与Eclipse集成,方便地管理web,java项目等等:但是很多初学者都不知道怎 ...
- 使用自定义的按钮替换默认的<input type='file'>
可以通过让默认的input type = 'file'按钮透明度变为0,并且让它刚好覆盖在自定义的按钮上,来实现此效果: 将它写成一个jQuery插件: (function($){ $.fn.brow ...
- js 取父级 页面上的元素
var bb=window.opener.frames["contentIframe"].document.all["my:费用类别"][0].value; / ...
- Oracle中文字符乱码?设置Oracle客户端字符编码与服务端一致
经常可能出现查询Oracle数据时,中文显示乱码,这很可能是因为,Oracle服务端的字符编码与客户端不一致引起的. 这时,我们需要做的是,如何设置自己的客户端字符编码与服务端一致. 查询Oracle ...