android文件上传示例分享(android图片上传)

主要思路是调用系统文件管理器或者其他媒体采集资源来获取要上传的文件,然后将文件的上传进度实时展示到进度条中。

主Activity

代码如下:

package com.guotop.elearn.activity.app.yunpan.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.guotop.base.activity.BaseActivity;
import com.guotop.base.util.MyFile;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.item.YunPanUploadFileItem;

/**
 *
 *
 * @author: 李杨
 * @time: 2014-4-15下午4:29:35
 */
public class YunPanUploadFileActivity extends BaseActivity implements OnClickListener{

String userId, parentId;
    private final static int FILECHOOSER_RESULTCODE = 0;
//    private String openFileType="";
    private String mVideoFilePath,mPhotoFilePath,mVoiceFilePath;
    private Button chooseBtn,uploadBtn;
    private LinearLayout conterLayout;
    private String actionURL;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, this);
        setTitle("云盘上传文件");
        setContentView(R.layout.activity_yunpan_uploadfile);

userId = getIntent().getStringExtra("userId");
        parentId = getIntent().getStringExtra("parentId");
        actionURL = getIntent().getStringExtra("actionURL");

chooseBtn = (Button)findViewById(R.id.chooseBtn);
        uploadBtn = (Button)findViewById(R.id.uploadBtn);
        conterLayout = (LinearLayout)findViewById(R.id.conterLayout);

chooseBtn.setOnClickListener(this);
        uploadBtn.setOnClickListener(this);

}

@Override
    public void onClick(View v) {
        if(v.getId()==R.id.chooseBtn){
//            //选择文件       
            startActivityForResult(createDefaultOpenableIntent(), YunPanUploadFileActivity.FILECHOOSER_RESULTCODE);

//            Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
//            startActivityForResult(intent, YunPanUploadFileActivity.FILECHOOSER_RESULTCODE);

//              Intent intent = new Intent(Media.RECORD_SOUND_ACTION);
//            ((Activity) context).startActivityForResult(intent, YunPanUploadFileActivity.FILECHOOSER_RESULTCODE);
        }else if(v.getId()==R.id.uploadBtn){
            //上传文件

}
    }

/**
     * 创建上传文件
     */
    public void createUploadFileItem(String filePath){
//        View view = LayoutInflater.from(context).inflate(R.layout.activity_yunpan_uploadfile_item, null);

new YunPanUploadFileItem(context, conterLayout, filePath,actionURL);

}

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
    }

/**选择文件*/
    private Intent createDefaultOpenableIntent() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.putExtra(Intent.EXTRA_TITLE, "选择文件");
        i.setType("*/*");

Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(), createSoundRecorderIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "选择文件");
        return chooser;
    }

private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() + File.separator + "e-photos");
        cameraDataDir.mkdirs();
        mPhotoFilePath = cameraDataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPhotoFilePath)));
        return cameraIntent;
    }

private Intent createCamcorderIntent() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() + File.separator + "e-videos");
        cameraDataDir.mkdirs();
        mVideoFilePath = cameraDataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".3gp";
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mVideoFilePath)));
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video
        return intent;
    }

private Intent createSoundRecorderIntent() {
        Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() + File.separator + "e-voices");
        cameraDataDir.mkdirs();
        mVoiceFilePath = cameraDataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".amr";
        return intent;
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            Uri result= data == null || resultCode != RESULT_OK ? null :data.getData();
            if (result == null && data == null && resultCode == Activity.RESULT_OK) {
                File mMediaFile = null;;
                if(new File(mVideoFilePath).exists()){
                    mMediaFile = new File(mVideoFilePath);
                }else if(new File(mPhotoFilePath).exists()){
                    mMediaFile = new File(mPhotoFilePath);
                }else if(new File(mVoiceFilePath).exists()){
                    mMediaFile = new File(mVoiceFilePath);
                }
                if (mMediaFile!=null&&mMediaFile.exists()) {
                    result = Uri.fromFile(mMediaFile);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                }
//                result = Uri.fromFile(new File(mCameraFilePath));
            }
            if(result!=null){
                if(!new File(result.getPath()).canRead()){
                    try {
                        MyFile.copyFile(new File(mVoiceFilePath),getContentResolver().openInputStream(result));
                        createUploadFileItem(mVoiceFilePath);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else {
                    createUploadFileItem(result.getPath());
                }
            }

System.out.println(result);
        }
    }

}

绘制现在文件信息后的Item


代码如下:

package com.guotop.elearn.activity.app.yunpan.item;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.guotop.base.L;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.HttpThread;
import com.guotop.base.util.MyFile;
import com.guotop.base.util.MyHashMap;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.Y;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunFileInformaction;
import com.guotop.elearn.activity.app.yunpan.thread.UploadYunFileHttpThread;

/**
 *
 *
 * @author: 李杨
 * @time: 2014-4-21下午12:28:33
 */
public class YunPanUploadFileItem implements OnClickListener {

LinearLayout view,parentView;
    String filePath;

private Context context;

private TextView uploadFileProgressText, uploadFileName;
    private ProgressBar uploadFileProgressBar;
    private ImageView uploadFileImg;
    private Button startUploadFileBtn, cancelUploadFileBtn;

private String actionURL;

BaseHandler handler;
    UploadYunFileHttpThread t;
    UploadYunFileInformaction uploadYunFileInformaction ;

public YunPanUploadFileItem(Context context,LinearLayout parentView, String filePath,String actionURL) {
        this.parentView = parentView;
        this.actionURL = actionURL;
        this.context = context;

File file = new File(filePath);

this.view = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.activity_yunpan_uploadfile_item, null);

//        this.view = view;
        this.filePath = filePath;

uploadFileProgressText = (TextView) view.findViewById(R.id.uploadFileProgressText);
        uploadFileName = (TextView) view.findViewById(R.id.uploadFileName);

uploadFileProgressBar = (ProgressBar) view.findViewById(R.id.uploadFileProgressBar);
        uploadFileImg = (ImageView) view.findViewById(R.id.uploadFileImg);

cancelUploadFileBtn = (Button) view.findViewById(R.id.cancelUploadFileBtn);
        startUploadFileBtn = (Button) view.findViewById(R.id.startUploadFileBtn);

uploadFileName.setText(file.getName()+"   大小"+MyFile.formetFileSize(file.getPath()));
        uploadFileImg.setImageResource(MyFile.getFileIcon(file));

startUploadFileBtn.setOnClickListener(this);
        cancelUploadFileBtn.setOnClickListener(this);
        parentView.addView(view);

uploadYunFileInformaction = new UploadYunFileInformaction(filePath);
        myHandler = new MyHandler(Looper.myLooper(), this);
        uploadYunFileInformaction.setNotificationId(new Random().nextInt(10000));
        uploadYunFileInformaction.setActionURL(actionURL);
        t = new UploadYunFileHttpThread(myHandler, uploadYunFileInformaction);
        uploads.put(uploadYunFileInformaction.getNotificationId(), t);

}

@Override
    public void onClick(View v) {
        if (v.getId() == R.id.startUploadFileBtn) {
            downFile(t);
            startUploadFileBtn.setClickable(false);
        }else if(v.getId()==R.id.cancelUploadFileBtn){
            if(t.isStart){
                new AlertDialog.Builder(context).setTitle("系统提示!").setMessage("该文件正在上传确定要强制停止?")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                t.interrupt();
                                parentView.removeView(view);
                                uploads.removeKey(uploadYunFileInformaction.getNotificationId());
                                System.gc();
                            }
                        }).show();
            }else {

parentView.removeView(view);
                uploads.removeKey(uploadYunFileInformaction.getNotificationId());
            }
        }
    }

public static MyHashMap<Integer, UploadYunFileHttpThread> uploads = new MyHashMap<Integer, UploadYunFileHttpThread>();

private MyHandler myHandler;

public IBinder onBind(Intent intent) {
        return null;
    }

// 下载更新文件
    private void downFile(UploadYunFileHttpThread t) {
        int len = 3;

if (t != null && uploads.size() <= len) {
            if (!t.isStart) {
                t.start();
            }
        } else if (t == null && uploads.size() >= len) {
            t = uploads.get(len - 1);
            if (!t.isStart) {
                t.start();
            }
        }
    }

/* 事件处理类 */
    class MyHandler extends BaseHandler {
        private WeakReference<YunPanUploadFileItem> bdfs;

public MyHandler(Looper looper, YunPanUploadFileItem yunPanUploadFileItem) {
            super(looper);
            this.bdfs = new WeakReference<YunPanUploadFileItem>(yunPanUploadFileItem);
        }

@Override
        public void handleMessage(Message msg) {
            YunPanUploadFileItem bdfs = this.bdfs.get();
            if (bdfs == null) {
                return;
            }
            if (msg != null) {
                switch (msg.what) {
                case 0:
                    Toast.makeText(L.livingActivity, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case L.dowloadStart:
                    break;
                case L.dowloadFinish:
                    // 下载完成后清除所有下载信息,执行安装提示
                    try {
                        uploads.removeKey(msg.getData().getInt("notificationId"));

bdfs.uploadFileProgressText.setText("上传完成");
                        bdfs.uploadFileProgressBar.setMax(100);
                        bdfs.uploadFileProgressBar.setProgress(100);
                        startUploadFileBtn.setClickable(false);

} catch (Exception e) {

}
                    bdfs.downFile(null);
                    break;
                case L.dowloadPercentage:
                    // 更新状态栏上的下载进度信息
                    bdfs.uploadFileProgressText.setText("总共:"+MyFile.formetFileSize(msg.getData().getInt("fileSize"))+ "/" + MyFile.formetFileSize(msg.getData().getInt("finishFileSize")) + "  已上传"
                            + msg.getData().getInt("percentage") + "%");
                    bdfs.uploadFileProgressBar.setMax(100);
                    bdfs.uploadFileProgressBar.setProgress(msg.getData().getInt("percentage"));
                    break;
                case 4:
                    // bdfs.nm.cancel(msg.getData().getInt("notificationId"));
                    break;
                }

}
        }
    }

}

用来上传文件的线程

代码如下:

package com.guotop.elearn.activity.app.yunpan.thread;

import java.net.SocketException;

import com.guotop.base.L;
import com.guotop.base.Util;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.HttpThread;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunFileInformaction;
import com.guotop.elearn.activity.app.yunpan.util.YunPanUploadFile;
import com.guotop.elearn.activity.app.yunpan.util.YunPanUploadFileHttpInterface;

/**
 *
 * 下载云服务器上的文件
 *
 *
 *@author: 李杨
 *@time: 2014-4-11下午6:06:53
 */
public class UploadYunFileHttpThread extends HttpThread{

@SuppressWarnings("unused")
    private UploadYunFileInformaction uploadYunFileInformaction;

public boolean isStart=false;

public static int RECONNECT = 1000002;
    public static int CAN_NOT_RECONNECT = 1000003;

YunPanUploadFile yunPanUploadFile;

public UploadYunFileHttpThread(){

}

public UploadYunFileHttpThread(BaseHandler handler,UploadYunFileInformaction dowFile){
        this.uploadYunFileInformaction=dowFile;
        this.handler=handler;
    }

int fileSize,finishFileSize,percentage;

private boolean isUpdate = true;
    public void run() {
        isStart=true;//是启动了
        new HttpThread(handler){
            public void run() {
                while (isUpdate) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {

}
                    if(finishFileSize!=0&&fileSize!=0){
                        msg = handler.obtainMessage();
                        if(percentage>=100){
//                            msg.what=L.dowloadFinish;
//                            msg.setData(bundle);
//                            handler.sendMessage(msg);
                            break;
                        }else {
                            bundle.putString("fileName", uploadYunFileInformaction.getFileName());
                            bundle.putInt("percentage", percentage);
                            bundle.putInt("finishFileSize", finishFileSize);
                            bundle.putInt("fileSize", fileSize);
                            msg.what=L.dowloadPercentage;
                            msg.setData(bundle);
                            handler.sendMessage(msg);
                            sendMessage(1000000);// 为了取消等待框
                        }
                    }
                }
            }
        }.start();

try {
            uploadFile();
        } catch (Exception e) {
            isUpdate = false;
            isStart = false;
        }
    }

private void uploadFile() {
        yunPanUploadFile = new YunPanUploadFile(dbfInterface, uploadYunFileInformaction, L.COOKIE);
        result = yunPanUploadFile.post();

msg = handler.obtainMessage();
        bundle.putInt("notificationId", uploadYunFileInformaction.getNotificationId());
        bundle.putString("path", uploadYunFileInformaction.getPath());
        bundle.putString("result", result);
        msg.what = L.dowloadFinish;
        msg.setData(bundle);
        handler.sendMessage(msg);
        isUpdate = false;
        isStart = false;
    }

YunPanUploadFileHttpInterface dbfInterface = new YunPanUploadFileHttpInterface() {

//初始化下载后
        public void initFileSize(int size) {
            fileSize=size;
            msg = handler.obtainMessage();
            bundle.putInt("fileSize", fileSize);
            msg.what = L.dowloadStart;
            msg.setData(bundle);
            handler.sendMessage(msg);
        }
        //现在计划进行中
        public void uploadPlan(int fileSize,int finishSize) {
            finishFileSize=finishSize;
            percentage=finishSize/(fileSize/100);
            if(percentage<-1L){
                Util.LogGL(this.getClass().getName(), "downloadPlan",percentage+"");
            }
        }
        //下载完成
        public void uploadFinish(String file) {
            percentage=101;
        }
    };

public UploadYunFileInformaction getDowloadFileInformaction() {
        return uploadYunFileInformaction;
    }
    public void setDowloadFileInformaction(
            UploadYunFileInformaction dowloadFileInformaction) {
        this.uploadYunFileInformaction = dowloadFileInformaction;
    }

@Override
    public void interrupt() {
        yunPanUploadFile.close();
        super.interrupt();
    }

}

记录文件信息Bean

代码如下:

package com.guotop.elearn.activity.app.yunpan.item;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.guotop.base.L;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.HttpThread;
import com.guotop.base.util.MyFile;
import com.guotop.base.util.MyHashMap;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.Y;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunFileInformaction;
import com.guotop.elearn.activity.app.yunpan.thread.UploadYunFileHttpThread;

/**
 *
 *
 * @author: 李杨
 * @time: 2014-4-21下午12:28:33
 */
public class YunPanUploadFileItem implements OnClickListener {

LinearLayout view,parentView;
    String filePath;

private Context context;

private TextView uploadFileProgressText, uploadFileName;
    private ProgressBar uploadFileProgressBar;
    private ImageView uploadFileImg;
    private Button startUploadFileBtn, cancelUploadFileBtn;

private String actionURL;

BaseHandler handler;
    UploadYunFileHttpThread t;
    UploadYunFileInformaction uploadYunFileInformaction ;

public YunPanUploadFileItem(Context context,LinearLayout parentView, String filePath,String actionURL) {
        this.parentView = parentView;
        this.actionURL = actionURL;
        this.context = context;

File file = new File(filePath);

this.view = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.activity_yunpan_uploadfile_item, null);

//        this.view = view;
        this.filePath = filePath;

uploadFileProgressText = (TextView) view.findViewById(R.id.uploadFileProgressText);
        uploadFileName = (TextView) view.findViewById(R.id.uploadFileName);

uploadFileProgressBar = (ProgressBar) view.findViewById(R.id.uploadFileProgressBar);
        uploadFileImg = (ImageView) view.findViewById(R.id.uploadFileImg);

cancelUploadFileBtn = (Button) view.findViewById(R.id.cancelUploadFileBtn);
        startUploadFileBtn = (Button) view.findViewById(R.id.startUploadFileBtn);

uploadFileName.setText(file.getName()+"   大小"+MyFile.formetFileSize(file.getPath()));
        uploadFileImg.setImageResource(MyFile.getFileIcon(file));

startUploadFileBtn.setOnClickListener(this);
        cancelUploadFileBtn.setOnClickListener(this);
        parentView.addView(view);

uploadYunFileInformaction = new UploadYunFileInformaction(filePath);
        myHandler = new MyHandler(Looper.myLooper(), this);
        uploadYunFileInformaction.setNotificationId(new Random().nextInt(10000));
        uploadYunFileInformaction.setActionURL(actionURL);
        t = new UploadYunFileHttpThread(myHandler, uploadYunFileInformaction);
        uploads.put(uploadYunFileInformaction.getNotificationId(), t);

}

@Override
    public void onClick(View v) {
        if (v.getId() == R.id.startUploadFileBtn) {
            downFile(t);
            startUploadFileBtn.setClickable(false);
        }else if(v.getId()==R.id.cancelUploadFileBtn){
            if(t.isStart){
                new AlertDialog.Builder(context).setTitle("系统提示!").setMessage("该文件正在上传确定要强制停止?")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                t.interrupt();
                                parentView.removeView(view);
                                uploads.removeKey(uploadYunFileInformaction.getNotificationId());
                                System.gc();
                            }
                        }).show();
            }else {

parentView.removeView(view);
                uploads.removeKey(uploadYunFileInformaction.getNotificationId());
            }
        }
    }

public static MyHashMap<Integer, UploadYunFileHttpThread> uploads = new MyHashMap<Integer, UploadYunFileHttpThread>();

private MyHandler myHandler;

public IBinder onBind(Intent intent) {
        return null;
    }

// 下载更新文件
    private void downFile(UploadYunFileHttpThread t) {
        int len = 3;

if (t != null && uploads.size() <= len) {
            if (!t.isStart) {
                t.start();
            }
        } else if (t == null && uploads.size() >= len) {
            t = uploads.get(len - 1);
            if (!t.isStart) {
                t.start();
            }
        }
    }

/* 事件处理类 */
    class MyHandler extends BaseHandler {
        private WeakReference<YunPanUploadFileItem> bdfs;

public MyHandler(Looper looper, YunPanUploadFileItem yunPanUploadFileItem) {
            super(looper);
            this.bdfs = new WeakReference<YunPanUploadFileItem>(yunPanUploadFileItem);
        }

@Override
        public void handleMessage(Message msg) {
            YunPanUploadFileItem bdfs = this.bdfs.get();
            if (bdfs == null) {
                return;
            }
            if (msg != null) {
                switch (msg.what) {
                case 0:
                    Toast.makeText(L.livingActivity, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case L.dowloadStart:
                    break;
                case L.dowloadFinish:
                    // 下载完成后清除所有下载信息,执行安装提示
                    try {
                        uploads.removeKey(msg.getData().getInt("notificationId"));

bdfs.uploadFileProgressText.setText("上传完成");
                        bdfs.uploadFileProgressBar.setMax(100);
                        bdfs.uploadFileProgressBar.setProgress(100);
                        startUploadFileBtn.setClickable(false);

} catch (Exception e) {

}
                    bdfs.downFile(null);
                    break;
                case L.dowloadPercentage:
                    // 更新状态栏上的下载进度信息
                    bdfs.uploadFileProgressText.setText("总共:"+MyFile.formetFileSize(msg.getData().getInt("fileSize"))+ "/" + MyFile.formetFileSize(msg.getData().getInt("finishFileSize")) + "  已上传"
                            + msg.getData().getInt("percentage") + "%");
                    bdfs.uploadFileProgressBar.setMax(100);
                    bdfs.uploadFileProgressBar.setProgress(msg.getData().getInt("percentage"));
                    break;
                case 4:
                    // bdfs.nm.cancel(msg.getData().getInt("notificationId"));
                    break;
                }

}
        }
    }

}

文件上传工具类

代码如下:

package com.guotop.elearn.activity.app.yunpan.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import android.R.integer;

import com.guotop.elearn.activity.app.yunpan.bean.UploadYunFileInformaction;

/**
 *
 *
 *
 * @author: 李杨
 * @time: 2013-6-13下午7:07:36
 */
public class YunPanUploadFile {
    String multipart_form_data = "multipart/form-data";
    String twoHyphens = "--";
    String boundary = "****************SoMeTeXtWeWiLlNeVeRsEe"; // 数据分隔符
    String lineEnd = "\r\n";

YunPanUploadFileHttpInterface  yunPanUploadFileHttpInterface;
    UploadYunFileInformaction uploadYunFileInformaction;
    String cookie;

public YunPanUploadFile(YunPanUploadFileHttpInterface yunPanUploadFileHttpInterface,UploadYunFileInformaction uploadYunFileInformaction,String cookie){
        this.yunPanUploadFileHttpInterface = yunPanUploadFileHttpInterface;
        this.uploadYunFileInformaction = uploadYunFileInformaction;
        this.cookie = cookie;
    }

public void write(UploadYunFileInformaction file, DataOutputStream output) {
        FileInputStream in;
        try {
            if (file.getPath() != null && !"".equals(file.getPath())) {
                in = new FileInputStream(new File(file.getPath()));
                int fileSize= in.available();
                int readySize = 0;
                yunPanUploadFileHttpInterface.initFileSize(fileSize);
                byte[] b = new byte[1024];
                while (in.read(b) > 0) {
                    readySize+=b.length;
                    yunPanUploadFileHttpInterface.uploadPlan(fileSize, readySize);
                    output.write(b, 0, b.length);
                }
            }
            output.writeBytes(lineEnd);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/*
     * 构建表单字段内容,格式请参考HTTP 协议格式(用FireBug可以抓取到相关数据)。(以便上传表单相对应的参数值) 格式如下所示:
     * --****************fD4fH3hK7aI6 Content-Disposition: form-data;
     * name="action" // 一空行,必须有 upload
     */
    private void addFormField(Map<String, String> params, DataOutputStream output) {
        if (params != null) {
            for (Entry<String, String> param : params.entrySet()) {
                StringBuilder sb = new StringBuilder();
                sb.append(twoHyphens + boundary + lineEnd);
                sb.append("Content-Disposition: form-data; name=\"" + param.getKey() + "\"" + lineEnd);
                sb.append(lineEnd);
                sb.append(param.getValue() + lineEnd);
                try {
                    output.write(sb.toString().getBytes("utf-8"));// 发送表单字段数据
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

/**
     * 直接通过 HTTP 协议提交数据到服务器,实现表单提交功能。
     *
     * @param actionUrl
     *            上传路径
     * @param params
     *            请求参数key为参数名,value为参数值
     * @param uploadYunFileInformaction
     *            上传文件信息
     * @return 返回请求结果
     */

public String post(){
        return post(null,uploadYunFileInformaction, cookie);
    }

public String post(UploadYunFileInformaction uploadYunFileInformaction, String cookie,YunPanUploadFileHttpInterface yunPanUploadFileHttpInterface) {
        return post(null,uploadYunFileInformaction, cookie);
    }
    HttpURLConnection conn = null;
    DataOutputStream output = null;
    BufferedReader input = null;

public String post(Map<String, String> params, UploadYunFileInformaction uploadYunFileInformaction, String cookie) {

try {
            URL url = new URL(uploadYunFileInformaction.getActionURL());
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setConnectTimeout(120000);
            conn.setDoInput(true); // 允许输入
            conn.setDoOutput(true); // 允许输出
            conn.setUseCaches(false); // 不使用Cache
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Content-Type", multipart_form_data + "; boundary=" + boundary);
            conn.setChunkedStreamingMode(1024*1024);//设置上传文件的缓存大小
            conn.connect();
            output = new DataOutputStream(conn.getOutputStream());

//发送头数据
            sendSplitHead(uploadYunFileInformaction,output);

//发送文件内容
            write(uploadYunFileInformaction, output);

//发送表单数据
            addFormField(params, output); // 添加表单字段内容

output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);// 数据结束标志
            output.flush();

int code = conn.getResponseCode();
            if (code != 200) {
                throw new RuntimeException("请求‘" + uploadYunFileInformaction.getActionURL() + "'失败!");
            }

input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String oneLine;
            while ((oneLine = input.readLine()) != null) {
                response.append(oneLine + lineEnd);
            }
            yunPanUploadFileHttpInterface.uploadFinish(uploadYunFileInformaction.getPath());

return response.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            close();
        }
    }

public void close(){
        // 统一释放资源
        try {
            if (output != null) {
                output.close();
            }
            if (input != null) {
                input.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

if (conn != null) {
            conn.disconnect();
        }
    }

//发送头数据
    public void sendSplitHead(UploadYunFileInformaction uploadYunFileInformaction, DataOutputStream output){
        StringBuilder split = new StringBuilder();
        split.append(twoHyphens + boundary + lineEnd);
        try {
            split.append("Content-Disposition: form-data; name=\"" + uploadYunFileInformaction.getFormName() + "\"; filename=\""
                    + new String(uploadYunFileInformaction.getFileName().getBytes(),"iso8859-1") + "\"" + lineEnd);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        split.append("Content-Type: " + uploadYunFileInformaction.getContentType() + lineEnd);
        split.append(lineEnd);

// 发送数据
        try {
            output.writeBytes(split.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Layout 文件内容

activity_yunpan_uploadfile_item.xml

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:orientation="horizontal" >

<RelativeLayout
        android:id="@+id/titleLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top" >

<LinearLayout
            android:id="@+id/titleCenter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/titleRigth"
            android:layout_toRightOf="@+id/titelLeft"
            android:gravity="left"
            android:orientation="vertical" >

<TextView
                android:id="@+id/uploadFileProgressText"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="上传进度"
                android:textAppearance="?android:attr/textAppearanceLarge" />

<ProgressBar
                android:id="@+id/uploadFileProgressBar"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

<TextView
                android:id="@+id/uploadFileName"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="文件名称"
                android:textAppearance="?android:attr/textAppearanceLarge" />
        </LinearLayout>

<LinearLayout
            android:id="@+id/titelLeft"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignBaseline="@+id/titleCenter"
            android:layout_alignBottom="@+id/titleCenter"
            android:layout_alignParentLeft="true"
            android:orientation="vertical" >
        </LinearLayout>

<LinearLayout
            android:id="@+id/titleRigth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="21dp"
            android:orientation="horizontal" >

<Button
                android:id="@+id/startUploadFileBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="开始" />

<Button
                android:id="@+id/cancelUploadFileBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="取消" />
        </LinearLayout>

<ImageView
            android:id="@+id/uploadFileImg"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/titleCenter" />
    </RelativeLayout>

</LinearLayout>

activity_yunpan_uploadfile.xml

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<RelativeLayout
        android:id="@+id/titleLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top" >

<!--         <LinearLayout -->
<!--             android:id="@+id/titleRigth" -->
<!--             android:layout_width="wrap_content" -->
<!--             android:layout_height="wrap_content" -->
<!--             android:layout_alignBaseline="@+id/titleCenter" -->
<!--             android:layout_alignBottom="@+id/titleCenter" -->
<!--             android:layout_alignParentRight="true" -->
<!--             android:orientation="vertical" > -->

<!--             <Button -->
<!--                 android:layout_width="wrap_content" -->
<!--                 android:layout_height="wrap_content" -->
<!--                 android:text="titleRigth" /> -->

<!--         </LinearLayout> -->

<!--         <LinearLayout -->
<!--             android:id="@+id/titleCenter" -->
<!--             android:layout_width="wrap_content" -->
<!--             android:layout_height="wrap_content" -->
<!--             android:layout_alignParentTop="true" -->
<!--             android:layout_toLeftOf="@+id/titleRigth" -->
<!--             android:layout_toRightOf="@+id/titelLeft" -->
<!--             android:gravity="left" -->
<!--             android:orientation="vertical" > -->

<!--             <Button -->
<!--                 android:layout_width="fill_parent" -->
<!--                 android:layout_height="wrap_content" -->
<!--                 android:text="titleCenter" /> -->
<!--         </LinearLayout> -->

<LinearLayout
            android:id="@+id/titelLeft"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/titleCenter"
            android:layout_alignBottom="@+id/titleCenter"
            android:layout_alignParentLeft="true"
            android:orientation="horizontal" >

<Button
                android:id="@+id/chooseBtn"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="选择文件" />

<Button
                android:id="@+id/uploadBtn"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="全部开始上传" />
        </LinearLayout>

</RelativeLayout>

<RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

<ScrollView
            android:id="@+id/scrollView1"
            android:layout_above="@+id/bottom"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

<LinearLayout
                android:id="@+id/conterLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="top"
                android:orientation="vertical" >
            </LinearLayout>
        </ScrollView>

<LinearLayout
            android:id="@+id/bottom"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:gravity="bottom"
            android:orientation="vertical" >
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>

(0)

相关推荐

  • Android中发送Http请求(包括文件上传、servlet接收)的实例代码

    复制代码 代码如下: /*** 通过http协议提交数据到服务端,实现表单提交功能,包括上传文件* @param actionUrl 上传路径 * @param params 请求参数 key为参数名,value为参数值 * @param file 上传文件 */public static void postMultiParams(String actionUrl, Map<String, String> params, FormBean[] files) {try {PostMethod p

  • Android实现本地上传图片并设置为圆形头像

    先从本地把图片上传到服务器,然后根据URL把头像处理成圆形头像. 因为上传图片用到bmob的平台,所以要到bmob(http://www.bmob.cn)申请密钥. 效果图: 核心代码: 复制代码 代码如下: public class MainActivity extends Activity {         private ImageView iv;         private String appKey="";                //填写你的Applicatio

  • Android仿微信发表说说实现拍照、多图上传功能

    本文实例为大家分享了Android仿微信发表说说.心情功能,供大家参考,具体内容如下 既能实现拍照,选图库,多图案上传的案例,目前好多App都有类似微信朋友圈的功能,能过发表说说等附带图片上传.下面的就是实现该功能的过程:大家还没有看过Android Retrofit 2.0框架上传图片解决方案这篇文章,在看今天的就很容易,接在本项目中用到了一个library:photopicker,封装了图片的选择功能,是否选相机,还有选中图片后可以查看图片的功能.  一. 首先:将photopicker到工

  • Android Retrofit 2.0框架上传图片解决方案

    本文为大家分享了 Android Retrofit 2.0框架上传图片解决方案,具体内容如下 1.单张图片的上传 /** * 上传一张图片 * @param description * @param imgs * @return */ @Multipart @POST("/upload") Call<String> uploadImage(@Part("fileName") String description, @Part("file\&qu

  • android 捕获系统异常并上传日志具体实现

    在做项目时,经常会把错误利用异常抛出去,这样在开发时就可以通过手机抛出的异常排查错误.但是当程序开发完毕,版本稳定,需要上线时,为了避免抛出异常影响用户感受,可以用UncaughtExceptionHandler捕获全局异常,对异常做出处理.比如我们可以获取到抛出异常的时间.手机的硬件信息.错误的堆栈信息,然后将获取到的所有的信息发送到服务器中,也可以发送到指定的邮件中,以便及时修改bug. 示例: 自定义异常类实现UncaughtExceptionHandler接口,当某个页面出现异常就会调用

  • android 拍照和上传的实现代码

    复制代码 代码如下: import java.io.ByteArrayOutputStream;   import java.io.File;   import android.app.Activity;   import android.content.Intent;   import android.graphics.Bitmap;   import android.net.Uri;   import android.os.Bundle;   import android.os.Enviro

  • android 上传文件到服务器代码实例

    android对于上传文件,还是很简单的,和java里面的上传都是一样的,基本上都是熟悉操作输出流和输入流!还有一个特别重要的就是需要一些content-type这些参数的配置!  如果这些都弄好了,上传就很简单了!   下面是我写的一个上传的工具类: 复制代码 代码如下: package com.spring.sky.image.upload.network; import java.io.DataOutputStream;import java.io.File;import java.io.

  • Android实现上传文件功能的方法

    本文所述为一个Android上传文件的源代码,每一步实现过程都备有详尽的注释,思路比较清楚,学习了本例所述上传文件代码之后,你可以应对其它格式文件的上传.实例中主要实现上传文件至Server的方法,允许Input.Output,不使用Cache,使Androiod上传文件变得轻松. 主要功能代码如下: package com.test; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.

  • SimpleCommand实现上传文件或视频功能(四)

    上传文件的核心功能主要是在UploadCommand.java中实现 使用步骤: 1 创建UploadCommand的构建类Builder UploadCommand.Builder builder = new UploadCommand.Builder(); 2 通过构建类设置UploadCommand的各种属性 builder.domain("上传地址的域名") .path("上传接口") .contentType("请求头文件的Content-typ

  • Android使用post方式上传图片到服务器的方法

    本文实例讲述了Android使用post方式上传图片到服务器的方法.分享给大家供大家参考,具体如下: /** * 上传文件到服务器类 * * @author tom */ public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CH

随机推荐