Android 阿里云日志上传

转载:https://blog.csdn.net/fangziyi199110/article/details/103751347

工具类

/**
 * Created by EDZ on 2020/9/23.
 * Describe:工具类
 */
public class OssManager {
    /**
     * Context
     */
    private Context mContext;
    /**
     * bucket name
     */
    private String mBucketName;
    /**
     * access key id
     */
    private String mAccessKeyId;
    /**
     * access key secret
     */
    private String mAccessKeySecret;
    /**
     * end point url
     */
    private String mEndPoint;
    /**
     * file name or file dir
     */
    private String mObjectKey;
    /**
     * local file path
     */
    private String mLocalFilePath;
    /**
     * push file progress listener
     */
    private OnPushProgressListener onPushProgressListener;
    /**
     * push file state
     */
    private OnPushStateListener onPushStateListener;
    /**
     * OSS async task
     */
    private OSSAsyncTask mOSSAsyncTask;

    private OssManager(Context context, String bucketName, String accessKeyId,
                       String accessKeySecret, String endPoint, String objectKey, String localFilePath) {
        this.mContext = context;
        this.mBucketName = bucketName;
        this.mAccessKeyId = accessKeyId;
        this.mAccessKeySecret = accessKeySecret;
        this.mEndPoint = endPoint;
        this.mObjectKey = objectKey;
        this.mLocalFilePath = localFilePath;
        push();
    }

    /**
     * set push file progress listener,pushing call back onProgress(PutObjectRequest request, long currentSize, long totalSize)
     *
     * @param listener push file progress listener
     */
    public void setPushProgressListener(OnPushProgressListener listener) {
        this.onPushProgressListener = listener;
    }

    /**
     * set push file state listener,push success call back onSuccess(PutObjectRequest request, PutObjectResult result)
     * push failed call back onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException)
     *
     * @param listener push file state listener
     */
    public void setPushStateListener(OnPushStateListener listener) {
        this.onPushStateListener = listener;
    }

    /**
     * push file to oss,this method is async task
     */
    public void push() {
        OSSCredentialProvider ossCredentialProvider = new OSSPlainTextAKSKCredentialProvider(mAccessKeyId, mAccessKeySecret);
        OSS oss = new OSSClient(mContext.getApplicationContext(), mEndPoint, ossCredentialProvider);
        onPush(oss);
    }

    /**
     * push file to oss,this method is async task
     */
    public void push(String accessKeyId, String accessKeySecret, String securityToken) {
        if (accessKeyId == null || accessKeySecret == null || securityToken == null) return;
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        OSS oss = new OSSClient(mContext.getApplicationContext(), mEndPoint, credentialProvider);
        onPush(oss);
    }

    /**
     * push
     * @param oss OSS
     */
    private void onPush(OSS oss) {
        PutObjectRequest put = new PutObjectRequest(mBucketName, mObjectKey, mLocalFilePath);
        // 异步上传时可以设置进度回调。
//        put.setProgressCallback((request, currentSize, totalSize) -> {
//            Log.e("currentSize = " + currentSize, "totalSize = " + totalSize);
//            if (onPushProgressListener != null) {
//                onPushProgressListener.onProgress(request, currentSize, totalSize);
//            }
//        });
// 此处调用异步上传方法
//        OSSAsyncTask ossAsyncTask= oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
//                    @Override
//                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                        Log.d("PutObject", "UploadSuccess");
//                        Log.d("ETag", result.getETag());
//                        Log.d("RequestId", result.getRequestId());
//                    }}

        mOSSAsyncTask = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.e("PutObject", "UploadSuccess");
                Log.e("ETag", result.getETag());
                Log.e("RequestId", result.getRequestId());
                if (onPushStateListener != null) {
                    onPushStateListener.onSuccess(request, result);
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                // 请求异常。
                if (clientException != null) {
                    // 本地异常,如网络异常等。
                    Log.e("异常:",clientException.getMessage());
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());

                }

                if (onPushStateListener != null) {
                    onPushStateListener.onFailure(request, clientException, serviceException);
                }
            }
        });
    }

    /**
     * cancel file push task
     */
    public void cancelPush() {
        if (mOSSAsyncTask != null && !mOSSAsyncTask.isCanceled() && !mOSSAsyncTask.isCompleted()) {
            mOSSAsyncTask.cancel();
        }
    }

    /**
     * OssManager builder,init params
     */
    public static class Builder {

        private Context context;
        private String bucketName;
        private String accessKeyId;
        private String accessKeySecret;
        private String endPoint;
        private String objectKey;
        private String localFilePath;

        public Builder(Context context) {
            this.context = context;
        }

        public Builder bucketName(String bucketName) {
            this.bucketName = bucketName;
            return this;
        }

        public Builder accessKeyId(String accessKeyId) {
            this.accessKeyId = accessKeyId;
            return this;
        }

        public Builder accessKeySecret(String accessKeySecret) {
            this.accessKeySecret = accessKeySecret;
            return this;
        }

        public Builder endPoint(String endPint) {
            this.endPoint = endPint;
            return this;
        }

        public Builder objectKey(String objectKey) {
            this.objectKey = objectKey;
            return this;
        }

        public Builder localFilePath(String localFilePath) {
            this.localFilePath = localFilePath;
            return this;
        }

        public OssManager build() {
            return new OssManager(context, bucketName, accessKeyId, accessKeySecret, endPoint, objectKey, localFilePath);
        }
    }

    public interface OnPushProgressListener {
        void onProgress(PutObjectRequest request, long currentSize, long totalSize);
    }

    public interface OnPushStateListener {
        void onSuccess(PutObjectRequest request, PutObjectResult result);

        void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException);
    }

}

 

 

调用

OssManager.Builder builder=new OssManager.Builder(MainActivity.this);
builder.accessKeyId("——————") ;//秘钥
builder.bucketName("位置");//存储位置http://这里的.oss-cn-shanghai.aliyuncs.com/applog/test.txt
builder.accessKeySecret("——————");//秘钥
builder.endPoint("http://oss-cn-shanghai.aliyuncs.com");//地域节点
builder.objectKey("applog/test.txt");//上传到某个文件夹内部文件
builder.localFilePath(mPicturePath);//上传本地文件路径
builder.build();

 

6.0读写权限申请
public static void verifyStoragePermissions(Activity activity) {

    try {
        //检测是否有写的权限
        int permission = ActivityCompat.checkSelfPermission(activity,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限,去申请写的权限,会弹出对话框
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

 

 

依赖

//阿里云
compile 'com.aliyun.dpa:oss-android-sdk:2.4.5'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'
implementation 'com.aliyun.dpa:oss-android-sdk:2.5.0'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public class GetAndUploadFileDemo { private static String TAG = "GetAndUploadFileDemo"; private OSSService ossService; private OSSBucket bucket; public void show() { ossService = OSSServiceProvider.getService(); bucket = ossService.getOssBucket("youcaidao"); // 文件的常规操作如普通上、下载、拷贝、删除等,与Data类一致,故这里只给出断点下载和断点上的demo resumableDownloadWithSpecConfig(); // delay(); // resumableUpload(); // delay(); // resumableDownload(); // delay(); } public void delay() { try { Thread.sleep(30 * 1000); } catch (Exception e) { e.printStackTrace(); } } // 断点上 public void resumableUpload() { // OSSData ossData = ossService.getOssData(sampleBucket, "sample-data"); // ossData.setData(data, "raw"); // 指定需要上的数据和它的类型 // ossData.enableUploadCheckMd5sum(); // 开启上MD5校验 // ossData.upload(); // 上失败将会抛出异常 OSSFile bigfFile = ossService.getOssFile(bucket, "de.jpg"); try { bigfFile.setUploadFilePath( "/storage/emulated/0/Android/data/com.qd.videorecorder/video/VMS_1439866564822.jpg", "image/jpg"); bigfFile.ResumableUploadInBackground(new SaveCallback() { @Override public void onSuccess(String objectKey) { Log.d(TAG, "[onSuccess] - " + objectKey + " upload success!"); } @Override public void onProgress(String objectKey, int byteCount, int totalSize) { Log.d(TAG, "[onProgress] - current upload " + objectKey + " bytes: " + byteCount + " in total: " + totalSize); } @Override public void onFailure(String objectKey, OSSException ossException) { Log.e(TAG, "[onFailure] - upload " + objectKey + " failed!\n" + ossException.toString()); ossException.printStackTrace(); ossException.getException().printStackTrace(); } }); } catch (FileNotFoundException e) { e.printStackTrace(); } } // 断点下载 public void resumableDownload() { OSSFile bigFile = ossService.getOssFile(bucket, "bigFile.dat"); bigFile.ResumableDownloadToInBackground( "/storage/sdcard0/src_file/bigFile.dat", new GetFileCallback() { @Override public void onSuccess(String objectKey, String filePath) { Log.d(TAG, "[onSuccess] - " + objectKey + " storage path: " + filePath); } @Override public void onProgress(String objectKey, int byteCount, int totalSize) { Log.d(TAG, "[onProgress] - current download: " + objectKey + " bytes:" + byteCount + " in total:" + totalSize); } @Override public void onFailure(String objectKey, OSSException ossException) { Log.e(TAG, "[onFailure] - download " + objectKey + " failed!\n" + ossException.toString()); ossException.printStackTrace(); } }); } // 设置相关参数的断点续 public void resumableDownloadWithSpecConfig() { OSSFile bigFile = ossService .getOssFile(bucket, "VMS_1439866564822.jpg"); ResumableTaskOption option = new ResumableTaskOption(); option.setAutoRetryTime(2); // 默认为2次,最大3次 option.setThreadNum(2); // 默认并发3个线程,最大5个 bigFile.ResumableDownloadToInBackground( "/storage/emulated/0/Android/data/com.qd.videorecorder/video/VMS_1439866564822.jpg", new GetFileCallback() { // /storage/emulated/0/DCIM/Camera/VID_20150803_173350.mp4 @Override public void onSuccess(String objectKey, String filePath) { System.out.println("[onSuccess] - " + objectKey + " storage path: " + filePath); } @Override public void onProgress(String objectKey, int byteCount, int totalSize) { System.out.println("[onProgress] - current download: " + objectKey + " bytes:" + byteCount + " in total:" + totalSize); } @Override public void onFailure(String objectKey, OSSException ossException) { System.out.println("[onFailure] - download " + objectKey + " failed!\n" + ossException.toString()); ossException.printStackTrace(); } }); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值