使用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 ...
随机推荐
- 【js】sort()
//为了实现排序,sort()方法会调用每个数组项的toString()转型方法,然后比较得到的字符串, //以确定如何排序.即使数组中的每一项都是数值,sort()方法比较的也是字符串, var v ...
- 转 selenium 自动下载文件
#coding=utf-8from selenium import webdriver #实例化一个火狐配置文件fp = webdriver.FirefoxProfile() #设置各项参数,参数可以 ...
- 转 虫师的selenium借助AutoIt识别上传(下载)详解
selenium借助AutoIt识别上传(下载)详解 2014-12-27 11:26 by 虫师, 755 阅读, 1 评论, 收藏, 编辑 AutoIt目前最新是v3版本,这是一个使用类似BAS ...
- PLSQL_Oracle基本概念总结(汇总)
2014-08-16 Created By BaoXinjian
- android检测网络连接状态示例讲解
网络的时候,并不是每次都能连接到网络,因此在程序启动中需要对网络的状态进行判断,如果没有网络则提醒用户进行设置 Android连接首先,要判断网络状态,需要有相应的权限,下面为权限代码(Andro ...
- Linux时间子系统(十六) clockevent
一.clock event控制的通用逻辑 1.产生clock event的设备 各种系统的timer硬件形形色色,不过在general clock event device layer,struct ...
- hibernate,动态更新,插入 dynamic-insert,dynamic-update 我有话要说 ---稍后整理
http://dreamzhong.iteye.com/blog/1207377 http://blog.csdn.net/hsuxu/article/details/8108326 @org.hib ...
- LaTeX 编辑软件WinEdt使用简要介绍
LaTeX 编辑软件WinEdt使用简要介绍 LaTeX 的起源非常牛逼,有一套书大家可能听说过<计算机程序设计艺术>,写了好几本.当然能在计算机方面写上艺术俩字的书恐怕不是我们一般人 ...
- spring cloud中通过配置文件自定义Ribbon负载均衡策略
一.Ribbon中的负载均衡策略 1.Ribbon中支持的负载均衡策略 AvailabilityFilteringRule:过滤掉那些因为一直连接失败的被标记为circuit tripped的后端se ...
- VS2008配置OpenGl 亲测可行
OpenGL作为当前主流的图形API之一,它在一些场合具有比DirectX更优越的特性.1.与C语言紧密结合.OpenGL命令最初就是用C语言函数来进行描述的,对于学习过C语言的人来讲,OpenGL是 ...