hotter
hotter
  • 发布:2017-05-04 14:27
  • 更新:2020-10-28 16:14
  • 阅读:2567

android 单个大文件断点续传

分类:5+ SDK

最近公司项目需求做大文件的单点续传

分享下

java类代码

后台异步切割文件 切完返回true

/**  
     * 切割文件保存到指定目录 根据指定名称保存   
     * @param pWebview  
     * @param array  
     */  
    public void cutFile(final IWebview pWebview, JSONArray array){  
        final String CallBackID = array.optString(0);  
        final String filePath = array.optString(2);  
        final String cutPath = array.optString(3);  

        AsyncTask<String, Void, String> execute = new AsyncTask<String, Void, String>() {  
            public void execute(String taskId, String filePath, String cutPath) {  
            }  

            @Override  
            protected String doInBackground(String... params) {  
                java.net.HttpURLConnection connection = null;  

                byte[] buffer = new byte[readStep];  
                FileInputStream file = null;  
                File f =new File(filePath);  
                String fileName=f.getName();  
                try {  
                    file = new FileInputStream(filePath);  
                    int len = 0;  
                    int AllLen = 0;  
                    try {  
                        FileInputStream fs = new FileInputStream(filePath);  
                        fileSize = fs.available();  
                        AllLen = fileSize / (readStep);  
                        if(fileSize % (readStep) > 0){  
                            AllLen++;  
                        }  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    int nowCount = 1;  
                    while ((len = file.read(buffer)) > 0) {  
                        String strFilePath = cutPath+fileName+".part";  
                        try {  
                            File cutfile = new File(strFilePath);  
                            if (!cutfile.exists()) {  
                                Log.e("TestFile", "Create the file:" + strFilePath);  
                                cutfile.getParentFile().mkdirs();  
                                cutfile.createNewFile();  
                            }  
                            RandomAccessFile raf = new RandomAccessFile(cutfile, "rwd");  
                            raf.seek(0);  
                            raf.write(buffer,0,(int)len);  
                            raf.close();  
                        } catch (Exception e) {  
                            Log.e("TestFile", "Error on write File:" + e);  
                        }  
                        nowCount++;  
                    };  
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  

                return "abc";  
            }  

            protected void onPostExecute(String result) {  
                Log.e("result",result);  
                if(result == "abc"){  
                    JSONArray newArray = new JSONArray();  
                    newArray.put(true);  
                    JSUtil.execCallback(pWebview, CallBackID, newArray, JSUtil.OK, true);  
                }  

            }  

        }.execute();  

    }

后台异步提交文件夹中所有文件碎片

/**  
     *  
     * @param pWebview  
     * @param array  
     *  
     *    taskId    temp[0]  
     *    AllLen    temp[1]  
     *    nowCount  temp[2]  
     */  
    public void sendTempFile(IWebview pWebview, JSONArray array){  
        String CallBackID = array.optString(0);  
        String cutPath = array.optString(1);  
        String URLPath = array.optString(2);  

        byte[] buffer = new byte[readStep];  
        File file = new File(cutPath);  
        File[] fs = file.listFiles();  
        for (File f : fs){  
            String newString = f.getName().toString().replace(".part","");  

            Pattern pen = Pattern.compile("_");  

            String[] temp = pen.split(newString);  

            String fileName = temp[3];  
            Log.e("fileName",temp[3]);  
            //获取文件大小  
            FileInputStream fst = null;  
            try {  
                fst = new FileInputStream(f.getPath());  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            }  
            try {  
                fileSize = fst.available();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            //执行异步上传提交  
            asyncSendTempFiles(URLPath+"&task_id="+temp[0]+"&fileSize="+fileSize,f.getPath(),fileName,buffer,0,Integer.parseInt(temp[1]),Integer.parseInt(temp[2]),pWebview,CallBackID);  
        }  
    }  

    public void asyncSendTempFiles(final String urlPath, final String filePath, final String fileName, final byte[] buffer, final int count, final int allLength, final int nowCount, final IWebview pWebview, final String CallBackID){  

        AsyncTask<String, Void, String> execute = new AsyncTask<String, Void, String>() {  
            public void execute(String urlPath, String filePath, String fileName, byte[] buffer, int count, int allLength, int nowCount) {  
            }  

            @Override  
            protected String doInBackground(String... params) {  
                java.net.HttpURLConnection connection = null;  

                try {  
                    Log.e("urlPath",urlPath+"&allLength="+allLength+"&nowCount="+nowCount+"&fileName="+URLEncoder.encode(fileName, "UTF-8"));  
                    URL url = new URL(urlPath+"&allLength="+allLength+"&nowCount="+nowCount+"&fileName="+URLEncoder.encode(fileName, "UTF-8"));  
                    connection = (java.net.HttpURLConnection) url.openConnection();  
                    connection.setRequestMethod("POST");  
                    connection.setUseCaches(false);  
                    connection.setDoOutput(true);  

                    FileInputStream is = new FileInputStream(filePath);  
                    byte[] b = new byte[is.available()];  
                    Log.e("available",is.available()+"");  
                    is.read(b);  
                    OutputStream os = connection.getOutputStream();  
                    os.write(b);  
                    os.flush();  
                    os.close();  
                    if(connection.getResponseCode() == 200){  
                        Log.e("ResponseMessage",connection.getResponseMessage());  
                        return changeInputStream(connection.getInputStream(),"UTF-8");  
                    }else{  
                    }  
                } catch (IOException e) {  
                    Log.e("urlPath","url error");  
                    e.printStackTrace();  
                }  
                return "";  
            }  

            protected void onPostExecute(String result) {  
                Log.e("result",result);  
                try {  
                    JSONObject jsonObject = new JSONObject(result);  
                    //int resultCode = jsonObject.getInt("resultcode");  
                    String data = jsonObject.getString("status");  
                    Log.e("result-data",data);  
                    if(data == "0"){  
                        //传输成功 删除当前文件  
                        File file=new File(filePath);  
                        //文件是否存在  
                        if(file.exists())  
                        {  
                            file.delete();  
                            Log.e("result-data","文件已经被删除了");  
                        }  
                    }  

                } catch (JSONException e) {  
                    Log.e("result",result);  
                    e.printStackTrace();  
                }  
//                JSONArray newArray = new JSONArray();  
//                newArray.put(result);  
//                JSUtil.execCallback(pWebview, CallBackID, newArray, JSUtil.OK, true);  

            }  

        }.execute();  
    }  

    /**  
     * 将一个输入流转换成指定编码的字符串  
     *  
     * @param inputStream  
     * @param encode  
     * @return  
     */  
    private static String changeInputStream(InputStream inputStream,  
                                            String encode) {  

        // 内存流  
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
        byte[] data = new byte[1024];  
        int len = 0;  
        String result = null;  
        if (inputStream != null) {  
            try {  
                while ((len = inputStream.read(data)) != -1) {  
                    byteArrayOutputStream.write(data, 0, len);  
                }  
                result = new String(byteArrayOutputStream.toByteArray(), encode);  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return result;  
    }  
1 关注 分享
漠

要回复文章请先登录注册

FullStack

FullStack

大文件切片、分块、分段、分片,数据可用于分块上传(ios、android):[https://ext.dcloud.net.cn/plugin?id=3319](https://ext.dcloud.net.cn/plugin?id=3319)
2020-10-28 16:14