天天看点

安卓上传指定目录的所有txt文件到阿里云oss

1.遍历指定目录的所有txt文件

/**
     * 获取指定目录内所有文件路径
     * @param dirPath 需要查询的文件目录
     * @param _type 查询类型,比如TXT什么的
     */
    public JSONArray getAllFiles(String dirPath[], String _type) {
        JSONArray fileList = new JSONArray();
        for(int i= 0 ;i<dirPath.length;i++){
            File f = new File(String.valueOf(getExternalFilesDir(dirPath[i])));
            if (!f.exists()) {//判断路径是否存在
                return null;
            }
            File[] files = f.listFiles();
            if(files==null){//判断权限
                return null;
            }
            for (File _file : files) {//遍历目录
                if(_file.isFile() && _file.getName().endsWith(_type)){
                    String _name=_file.getName();
                    String filePath = _file.getAbsolutePath();//获取文件路径
//                String fileName = _file.getName().substring(0,_name.length()-4);//获取文件名
                    String fileName = _file.getName();//获取文件名
//                Log.e("LOGCAT","fileName:"+fileName);
//                Log.e("LOGCAT","filePath:"+filePath);
                    try {
                        JSONObject _fInfo = new JSONObject();
                        _fInfo.put("name", fileName);
                        _fInfo.put("path", filePath);
                        fileList.put(_fInfo);
                    }catch (Exception e){
                    }
                } else if(_file.isDirectory()){//查询子目录
//                getAllFiles(_file.getAbsolutePath(), _type);
                } else{
                }
            }
        }

        return fileList;
    }      

2.上传的实现

/**
     * 
     * @param context
     * @param endpoint 找后端拿
     * @param bucketName 找后端拿
     * @param objectName 这个是要存在oss的文件名
     * @param uploadFilePath 这个是本地文件的路径
     */
    public void UploadFile(Context context,String endpoint, String bucketName, String objectName, final String uploadFilePath) {
        credentialProvider = new OSSAuthCredentialsProvider("https://xxx.cn");//这个找你们后端拿吧,是authServerUrl
        conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数,默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
        oss = new OSSClient(context, endpoint, credentialProvider, conf);
        // 构造上传请求。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, uploadFilePath);
        // 异步上传时可以设置进度回调。
        putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.e(TAG, "onProgress: "+currentSize*100/totalSize );
            }
        });
        OSSAsyncTask ossAsyncTask = oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.e(TAG, "onSuccess: "+result );
         
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常,如网络异常等。
                    clientExcepion.printStackTrace();
                    Log.e("123",clientExcepion+"");
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("123",serviceException+"");
                }
            }

        });
        // ossAsyncTask.cancel(); // 可以取消任务
        ossAsyncTask.waitUntilFinished(); // 等待任务完成
    }      

3.遍历所有指定的目录下的所有txt文件,并上传(随便举个例子)

private void upload(){
        String file[] = {"PPG","ACC","GYRO","RRI"};//这里是遍历含有"PPG","ACC","GYRO","RRI"的所有txt文件
       String  userId = 109;
        JSONArray arrayPPG =getAllFiles(file,".txt");
        for (int i=0;i<arrayPPG.length();i++) {
            try {
                JSONObject jsonObject = (JSONObject) arrayPPG.get(i);
                String path=jsonObject.getString("path");
                String name =jsonObject.getString("name");
                String pathName =jsonObject.getString("name").substring(0,3);//截取路径的前3个字符
                UploadFile(this,
                        "http://oss-xxx.com",//找你们后端拿
                        "xxx",//桶名,找你们后端拿
                        pathName+"/"+userId+"_"+name,
                        path);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
      
    }      

上传成功之后的效果:

安卓上传指定目录的所有txt文件到阿里云oss
安卓上传指定目录的所有txt文件到阿里云oss

对了,别忘了添加oss的依赖哦,这里我是把它打成aar了

安卓上传指定目录的所有txt文件到阿里云oss

就是拿oss上面的demo

安卓上传指定目录的所有txt文件到阿里云oss
安卓上传指定目录的所有txt文件到阿里云oss
fileTree(dir: 'libs', include: ['*.jar','*.aar'])