采用webservice接口上传大文件

原理很简单:用流的方式一次读取2M的数据,然后上传2M数据,然后再接着读2M上传2M 依次类推 直到全部上传完成 下面是主要方法的实现 

//一次读取2M的大小

//一次读取2M的大小

private int MAXLENTH=1024*1024*2;

 

try {
    long totallen = file.length();
    InputStream in = new FileInputStream(file);
    byte b[] = new byte[MAXLENTH];
    int len = 0;
    float readlen = 0;
    int count=0;//上传了多少次
    boolean isfirst=true;//服务端接口参数
    boolean isend = false;//服务端接口参数
    while((len=in.read(b))!=-1){    //当没有读取完时,继续读取
         readlen+=len;
        {

   //发送到服务端
            String uploadBuffer = new String(Base64.encode(b));
            LinkedHashMap<String,Object> hashMap=new LinkedHashMap<>();
            hashMap.put("name",file.getName());
            hashMap.put("base64",uploadBuffer);
            hashMap.put("len",len);
            if((totallen-readlen)==0){
                isend = true;
            }
            hashMap.put("isend",isend ? 1:);
            hashMap.put("isfirst",isfirst?1:0);
            isfirst=false;
            getResponseResult(hashMap);
            count+=1;

   //更新UI
            Message msg=handler.obtainMessage();
            msg.what=0x88;
            msg.arg1=(int)(readlen/totallen*100);
            handler.sendMessage(msg);
        }

        if(readlen>=totallen){
            break;
        }

    }
    Log.e("UoLoadFileTask","count=="+count);
    in.close();
catch (FileNotFoundException e) {
    e.printStackTrace();
    Log.e("UoLoadFileTask""FileNotFoundException e==" + e);
}catch (Exception e){
    Log.e("UoLoadFileTask","Exception e=="+e);
}

 

下面贴上服务端的源码

 public String dbxupload(String name,String base64,int len,int isend,int isfirst){

System.out.println(name);

if(isfirst==1){//第一次上传

upcache.remove(name);

}

BaseEntity entity = new BaseEntity();

FileOutputStream out =null;

try {

String dirpath = XMConts.TMPDIR_windows

+File.separator+"files"+File.separator+"dax/";

File f = new File(dirpath);

if(!f.exists())

f.mkdirs();

if(!upcache.containsKey(name)){

out = new FileOutputStream(

  new File(dirpath,name));

upcache.put(name, out);

}else{

out = (FileOutputStream) upcache.get(name);

}

System.out.println("uu.....");

byte[] b = FileUtils.decodeBase64(base64);

if(len>=0&&b.length>=0){

out.write(b, 0, len);

out.flush();

}

if(isend==1){//1是最后一个 

out.flush();

out.close();

upcache.remove(name);

System.out.println("isend");

}

} catch (Exception e) {

e.printStackTrace();

entity.setCode(XMConts.ErrorCode.DB_ERR.getCode());

entity.setErrorDesc(e.getMessage());

if(out!=null){

try {

out.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

return bean2Json(entity);

}


版权声明:本文为ning_gg原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。