阿里云Oss上传(Android版)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/github_37847975/article/details/80697355

写了个简单的阿里云Oss上传,封装成一个类,可以直接使用

首先在您的gradle中配置sdk:

dependencies {
    compile 'com.aliyun.dpa:oss-android-sdk:+'
}

然后确保您的 AndroidManifest.xml 文件中已经配置了这些权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

将OssService这个类复制到项目中,导入需要的包,日志包根据您项目自己更改。

public class OssService {

    private OSS oss;
    private String accessKeyId;
    private String bucketName;
    private String accessKeySecret;
    private String endpoint;
    private Context context;

    private ProgressCallback progressCallback;

    public OssService(Context context, String accessKeyId, String accessKeySecret, String endpoint, String bucketName) {
        this.context = context;
        this.endpoint = endpoint;
        this.bucketName = bucketName;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
    }


    public void initOSSClient() {
        //OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.SecurityToken>");
        //这个初始化安全性没有Sts安全,如需要很高安全性建议用OSSStsTokenCredentialProvider创建(上一行创建方式)多出的参数SecurityToken为临时授权参数
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
        conf.setMaxConcurrentRequest(8); // 最大并发请求数,默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次

        // oss为全局变量,endpoint是一个OSS区域地址
        oss = new OSSClient(context, endpoint, credentialProvider, conf);

    }


    public void beginupload(Context context, String filename, String path) {
        //通过填写文件名形成objectname,通过这个名字指定上传和下载的文件
        String objectname = filename;
        if (objectname == null || objectname.equals("")) {
            ToastUtils.showShort("文件名不能为空");
            return;
        }
        //下面3个参数依次为bucket名,Object名,上传文件路径
        PutObjectRequest put = new PutObjectRequest(bucketName, objectname, path);
        if (path == null || path.equals("")) {
            LogUtil.d("请选择图片....");
            //ToastUtils.showShort("请选择图片....");
            return;
        }
        LogUtil.d("正在上传中....");
        //ToastUtils.showShort("正在上传中....");
        // 异步上传,可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                LogUtil.d("currentSize: " + currentSize + " totalSize: " + totalSize);
                double progress = currentSize * 1.0 / totalSize * 100.f;

                if (progressCallback != null) {
                    progressCallback.onProgressCallback(progress);
                }
            }
        });
        @SuppressWarnings("rawtypes")
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtil.d("UploadSuccess");
                //ToastUtils.showShort("上传成功");
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                LogUtil.d("UploadFailure");
                ToastUtils.showShort("UploadFailure");
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    LogUtil.e("UploadFailure:表示向OSS发送请求或解析来自OSS的响应时发生错误。\n" +
                            "  *例如,当网络不可用时,这个异常将被抛出");
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    LogUtil.e("UploadFailure:表示在OSS服务端发生错误");
                    LogUtil.e("ErrorCode", serviceException.getErrorCode());
                    LogUtil.e("RequestId", serviceException.getRequestId());
                    LogUtil.e("HostId", serviceException.getHostId());
                    LogUtil.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        //task.cancel(); // 可以取消任务
        //task.waitUntilFinished(); // 可以等待直到任务完成
    }


    public ProgressCallback getProgressCallback() {
        return progressCallback;
    }

    public void setProgressCallback(ProgressCallback progressCallback) {
        this.progressCallback = progressCallback;
    }

    public interface ProgressCallback {
        void onProgressCallback(double progress);
    }

}

最后在您的Activity中如下调用

//初始化OssService类,参数分别是Content,accessKeyId,accessKeySecret,endpoint,bucketName(后4个参数是您自己阿里云Oss中参数)
OssService ossService = new OssService(mApplication.app(), accessKeyId, accessKeySecret, endpoint, bucketName);
//初始化OSSClient
ossService.initOSSClient();
//开始上传,参数分别为content,上传的文件名filename,上传的文件路径filePath
ossService.beginupload(content, filename, filePath);
//上传的进度回调
ossService.setProgressCallback(new OssService.ProgressCallback() {
           @Override
           public void onProgressCallback(final double progress) {
                  LogUtil.d("上传进度:"+progress);
                  runOnUiThread(new Runnable() {
                       @Override
                       public void run() {

                       }
                  });          
           }

为了向别人、向世界证明自己而努力拼搏,而一旦你真的取得了成绩,才会明白:人无须向别人证明什么,只要你能超越自己。

阅读更多

没有更多推荐了,返回首页