断点续传

最近项目中用到了断点续传的功能 把代码贴在这儿有需要的可以自取

public class FileBiz {
    
    int legth = 0;
    InputStream in = null;
    RandomAccessFile randomAccessFile ;
    int chunks=1;//这是切片的数量默认为1
    String fileType;//后缀
    String code ;//这是随机码
    int pos=0;//这是标示现在上传到哪个位置的标识符
    //code 是随机码
    YiErMerEvent.HttpEvent message =null;
    /**
     * 申请上传一个文件
     * api会自动检测是否以前上传过该文件(以文件的md5作为标识,和文件名等无关)
     * @method POST
     * param md5
     * param size int 文件大小
     * param chunks int 切片的总数量
     * param suffix string 文件后缀
     * param type int 1普通图片2证件图片
     * @url upload-apply
     * @return string
     * @status 200|401|500
     * @format
     * [
     *      'id'=>string(随机标识码,每次上传文件切片需要携带,服务器以该标识码辨识是哪个文件的切片)
     *      'uploaded'=>0|1 int 文件是否在服务器存在 0 不存在需要上传 1 已经存在不需要上传
     *      'path'=>string 如果uploaded是1 该变量存储了图片路径 如果uploaded是0 该变量为空
     *
     */
    public void upLoadApply(final int type, final String path, final YiErMerEvent.HttpEvent httpEvent) {
        final File file;
        if(httpEvent!=null){
            message=httpEvent;
        }
        final byte[] tempbyte = new byte[1024*512];
        file = new File(path);
        StringRequest request = new StringRequest(Request.Method.POST, Url.UPLODEAPPLY, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject jsonObject =new JSONObject(s.toString());
                    if(jsonObject.getInt("status")==200){
                        JSONObject jsonObject1=new JSONObject(jsonObject.getString("result").toString());
                        code=jsonObject1.getString("code");
                        //文件大小小于1MB不需要切片上传的情况
                        if(chunks==1){

                        }
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                Looper.prepare();
                                try {
                                    uploadThread();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                Looper.loop();
                            }
                            private void uploadThread() throws IOException {
                                int elseLenth=legth-(pos*1024*512);
                                System.out.println("ceshi----pos------   "+pos);
                                randomAccessFile = new RandomAccessFile(path, "rw");
                                randomAccessFile.seek(pos*1024*512);//将文件流的位置移动到pos字节处
                                //用于保存实际读取的字节数
                                AjaxParams params = new AjaxParams();
                                final ByteArrayInputStream stream ;
                                if(elseLenth<1024*512){
                                    byte[] tempbyteforelse=new byte[elseLenth];
                                    randomAccessFile.read(tempbyteforelse);
                                    System.out.println("ceshi----tempbyteforelselenth------   "+tempbyteforelse.length);
                                    System.out.println("ceshi----tempbyteforelselenth------   "+ Arrays.toString(tempbyteforelse));
                                    stream = new ByteArrayInputStream(tempbyteforelse);
                                    params.put("file", stream,String.valueOf(pos+1),"video/mp4"); // 提交字节流
                                }else{
                                    randomAccessFile.read(tempbyte);
                                    System.out.println("ceshi----tempbytelenth------   "+tempbyte.length);
                                    System.out.println("ceshi----tempbyteforelselenth------   "+ Arrays.toString(tempbyte));
                                    stream = new ByteArrayInputStream(tempbyte);
                                    params.put("file", stream,String.valueOf(pos+1),"video/mp4");// 提交字节流
                                }

                                FinalHttp fh = new FinalHttp();
                                fh.addHeader("token" , ShopApp.token);
                                fh.post(Url.UPLODEFILE+code, params, new AjaxCallBack<String>() {
                                    @Override
                                    public void onLoading(long count, long current) {
                                    }
                                    @Override
                                    public void onSuccess(String o) {
                                        super.onSuccess(o);
                                        try {
                                            stream.close();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                        try {
                                            JSONObject jsonObject = new JSONObject(o);
                                            if (pos >= chunks) {
                                                //传入数据  一次传完
                                                UplodeFinish(code);
                                                in.close();
                                                sessionId = "";
                                            } else {
                                                pos++;
                                                uploadThread();
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                            }
                        }.start();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println(volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = new HashMap<>();
                header.put("token", ShopApp.token);
                return header;
            }
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                String fileName=file.getName();
                String[] suffixs = fileName.split("\\.");
                fileType = suffixs[1];
                Map<String, String> params = new HashMap<>();
                params.put("md5", MD5.getFileMD5(file));
                params.put("suffix", fileType);
                params.put("type", String.valueOf(type));
                chunks=((int)FileSizeUtil.getFileSize(file)/(1024*512));
                legth=(int)FileSizeUtil.getFileSize(file);
                params.put("chunks", String.valueOf(chunks+1));
                System.out.println("ceshi----chunks------   "+chunks);
                params.put("size",  String.valueOf((int)FileSizeUtil.getFileSize(file)));
                return params;
            }
        };
        mQueue.add(request);
    }
    /**
     * 上传完成后调用服务器接口完成上传
     * type用处(register|login|resetpwd)
     */
    public void UplodeFinish(final String code) {
        iStringRequest request = new iStringRequest(Request.Method.PUT,
                Url.UPLODEFHINIS+code,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        message.what = 1;
                        try {
                            JSONObject jsonObject =new JSONObject(response.toString());
                            System.out.println("ceshi----finish------   "+jsonObject.get("status"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        EventBus.getDefault().post(message);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        message.what = -1;
                        message.errorCode = volleyError.networkResponse.statusCode;
                        EventBus.getDefault().post(message);
                    }
                }){
        }.addHeaders("token", ShopApp.token);
        mQueue.add(request);
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值