欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-05-27 10:25:15
主要思路是调用系统文件管理器或者其他媒体采集资源来获取要上传的文件,然后将文件的上传进度实时展示到进度条中。 主activity 复制代码 代码如下:package c...

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>