阿里 OSS 上传 工具类

完整路径  例如 : 

http://bucket.oss-cn-beijing.aliyuncs.com/hk/1236446565.jpg

路径包括 二部分 ,一部分 基路径   http://bucket.oss-cn-beijing.aliyuncs.com/ 是服务器申请后阿里给的 

第二部分 是文件路径 hk/1236446565.jpg 可以按业务关系 自己拼接 。(一般是文件路径+ 文件名称) 。

1.PutObjectRequest request = new PutObjectRequest(Constant.BUCKET, objectKey, file.getPath()); 

objectkey 是生成的网络路径 子路径 ,就是子路径 。

bucket 就是 基路径中 的 oss 前面的 

第三个参数 是本地文件的绝对路径 

2. ENDPOINT 是指定的阿里服务器地址,有北京 上海 杭州 等,申请成功后,在后台页面会给出。

 

 

package com.lsw.mvpframe.utils;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.lsw.mvpframe.BaseApplication;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;


/**
 * author: create by lsw
 *
 * description:
 */
public class OssServiceManager {

    private final OSSClient mOssClient;
    private static final String TAG = "OssServiceManager";
    private final String OssPrefix = null;

    private OssServiceManager(Context context) {
//        OSSCredentialProvider provider = new OSSCustomSignerCredentialProvider() {
//            @Override
//            public String signContent(String content) {
//                // 您需要在这里依照OSS规定的签名算法,实现加签一串字符内容,并把得到的签名传拼接上AccessKeyId后返回
//                // 一般实现是,将字符内容post到您的业务服务器,然后返回签名
//                // 如果因为某种原因加签失败,描述error信息后,返回nil
//                // 以下是用本地算法进行的演示
//                return OSSUtils.sign(OssConfig.AccessKeyId, OssConfig.getAccessKeySecret(), content);
//            }
//        };
        OSSCredentialProvider credentialProvider2 = new OSSPlainTextAKSKCredentialProvider("LTAIVIVf", "T2qzFeuwrng");


        //设置网络参数
        ClientConfiguration configuration = new ClientConfiguration();
        configuration.setConnectionTimeout(30 * 1000); // 连接超时,默认15秒
        configuration.setSocketTimeout(30 * 1000); // socket超时,默认15秒
        configuration.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
        configuration.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次

        mOssClient = new OSSClient(context, Constant.ENDPOINT, credentialProvider2, configuration);
        OSSLog.enableLog();
//        OssPrefix = BaseApplication.isdebug ? "test/android/" : "hb/android/" + YzUserManager.getUserId() + "/";
    }

    public static OssServiceManager getDefault() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static OssServiceManager INSTANCE = new OssServiceManager(BaseApplication.getInstance().getContext());
    }

    /**
     * 单个文件上传
     */
    public void asyncPut(@NonNull String localFilePath, @Nullable OSSSingleCallback callback) {
        File file = new File(localFilePath);
        if (!file.exists()) {
            LogUtil.e("file Not exist");
            return;
        }
        String objectKey = generateObjectKeyFromFile(file);
        // 构造上传请求
        PutObjectRequest request = new PutObjectRequest(Constant.BUCKET, objectKey, localFilePath);
        // 异步上传时可以设置进度回调
        request.setProgressCallback((request1, currentSize, totalSize) -> {
            if (callback != null) {
                float progress = currentSize * 1.0f / totalSize * 1.0f;

                Completable.fromAction(() -> callback.onProgress(progress))
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .subscribe();
            }
        });

        OSSAsyncTask<PutObjectResult> asyncTask = mOssClient.asyncPutObject(request, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                //移除执行完毕的任务
                mAsyncTaskMap.remove(request.getObjectKey());

                if (callback != null) {
                    Completable.fromAction(() -> callback.onSuccess(request, result))
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe();
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                //移除执行完毕的任务
                mAsyncTaskMap.remove(request.getObjectKey());

                // 请求异常
                if (clientException != null) {
                    // 本地异常如网络异常等
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    LogUtil.e(serviceException.getErrorCode());
                    LogUtil.e(serviceException.getRequestId());
                    LogUtil.e(serviceException.getHostId());
                    LogUtil.e(serviceException.getRawMessage());
                }
                if (callback != null) {
                    Completable.fromAction(callback::onError)
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe();
                }
            }
        });
        mAsyncTaskMap.put(objectKey, asyncTask);
    }

    public void asyncDelete(String objectKey) {
        DeleteObjectRequest request = new DeleteObjectRequest(Constant.BUCKET, objectKey);
        // 异步删除
        OSSAsyncTask<DeleteObjectResult> asyncTask = mOssClient.asyncDeleteObject(request, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
            @Override
            public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
                LogUtil.e("delete success");
                //移除执行完毕的任务
//                mAsyncTaskMap.remove(request.getObjectKey());
            }

            @Override
            public void onFailure(DeleteObjectRequest request, ClientException clientException, ServiceException serviceException) {
                //移除执行完毕的任务
//                mAsyncTaskMap.remove(request.getObjectKey());
                // 请求异常
                if (clientException != null) {
                    // 本地异常如网络异常等
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    LogUtil.e(serviceException.getErrorCode());
                    LogUtil.e(serviceException.getRequestId());
                    LogUtil.e(serviceException.getHostId());
                    LogUtil.e(serviceException.getRawMessage());
                }
            }
        });

//        mAsyncTaskMap.put(objectKey, asyncTask);
    }

    private int mPutCount;

    /**
     * key为objectKey,value为index和path
     */
    private Map<String, PathInfo> mPathInfoMap = new ConcurrentHashMap<>();

    /**
     * key为path,value未objectKey
     */
    private Map<String, String> mSuccessMap = new ConcurrentHashMap<>();

    /**
     * key为objectKey,value为当前下载进度和总进度
     */
    private Map<String, long[]> mProgressMap = new HashMap<>();

    private Map<String, OSSAsyncTask> mAsyncTaskMap = new ConcurrentHashMap<>();

    public void asyncMultiPut(@NonNull List<String> pathList, @Nullable OSSCallback callback) {
        multiReset();
        final int size = pathList.size();
        for (int i = 0; i < size; i++) {
            String path = pathList.get(i);
            File file = new File(path);
            if (!file.exists()) {
                LogUtil.e("file Not exist");
                return;
            }
            String objectKey = generateObjectKeyFromFile(file);
            mPathInfoMap.put(objectKey, new PathInfo(i, path));

            PutObjectRequest request = new PutObjectRequest(Constant.BUCKET, objectKey, file.getPath());
            request.setProgressCallback((request1, currentSize, totalSize) -> {
                mProgressMap.put(request1.getObjectKey(), new long[]{currentSize, totalSize});
//                if (callback != null && mProgressMap.size() == size) {
//                    long current = 0, total = 0;
//                    for (Map.Entry<String, long[]> entry : mProgressMap.entrySet()) {
//                        long[] value = entry.getValue();
//                        current += value[0];
//                        total += value[1];
//                    }
//                    float progress = current * 1.0f / total * 1.0f;
//                    if (progress > 1) {
//                        progress = 1;
//                    }
//                    final float finalProgress = progress;
                    LogUtil.e("进度回调=" + finalProgress);
                    Completable.fromAction(() -> callback.onProgress(finalProgress))
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe();
//                }
            });
            OSSAsyncTask<PutObjectResult> asyncTask = mOssClient.asyncPutObject(request, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                    AddCount();
                    String requestObjectKey = request.getObjectKey();

                    //移除执行完毕的任务
                    mAsyncTaskMap.remove(requestObjectKey);

                    String filePath = mPathInfoMap.get(requestObjectKey).path;

                    mSuccessMap.put(filePath, requestObjectKey);
                    LogUtil.e("requestObjectKey=" + requestObjectKey + "->filePath=" + filePath +" --> "+ mSuccessMap.size() +"  -- mPutCount " + mPutCount);
                    if (mPutCount == size) {
                        if (mSuccessMap.size() == size) {
                            //全部上传成功
                            fileSuccess(callback);
                        } else {
                            //部分上传成功
                            for (Map.Entry<String, String> entry : mSuccessMap.entrySet()) {
                                String value = entry.getValue();
                                asyncDelete(value);
                            }
                            multiReset();
                            if (callback != null) {
                                Completable.fromAction(()->callback.onError())
                                        .subscribeOn(AndroidSchedulers.mainThread())
                                        .subscribe();
                            }
                        }
                    }
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                    AddCount();
                    //移除执行完毕的任务
                    mAsyncTaskMap.remove(request.getObjectKey());

                    if (mPutCount == size) {
                        //上传失败
                        for (Map.Entry<String, String> entry : mSuccessMap.entrySet()) {
                            String value = entry.getValue();
                            asyncDelete(value);
                        }
                        multiReset();
                        if (callback != null) {
                            Completable.fromAction(callback::onError)
                                    .subscribeOn(AndroidSchedulers.mainThread())
                                    .subscribe();
                        }
                    }
                }
            });

            mAsyncTaskMap.put(objectKey, asyncTask);
        }
    }

    private synchronized void AddCount() {
        mPutCount++;
    }

    public void asyncMultiPutT(@NonNull List<String> pathList,String PRE_PATH , @Nullable OSSCallback callback) {
        multiReset();
        final int size = pathList.size();
        for (int i = 0; i < size; i++) {
            String path = pathList.get(i);
            File file = new File(path);
            if (!file.exists()) {
                LogUtil.e("file Not exist");
                return;
            }
            String objectKey = PRE_PATH + file.getName();
            mPathInfoMap.put(objectKey, new PathInfo(i, path));

            PutObjectRequest request = new PutObjectRequest(Constant.BUCKET, objectKey, file.getPath());
            request.setProgressCallback((request1, currentSize, totalSize) -> {
                mProgressMap.put(request1.getObjectKey(), new long[]{currentSize, totalSize});
//                if (callback != null && mProgressMap.size() == size) {
//                    long current = 0, total = 0;
//                    for (Map.Entry<String, long[]> entry : mProgressMap.entrySet()) {
//                        long[] value = entry.getValue();
//                        current += value[0];
//                        total += value[1];
//                    }
//                    float progress = current * 1.0f / total * 1.0f;
//                    if (progress > 1) {
//                        progress = 1;
//                    }
//                    final float finalProgress = progress;
                    LogUtil.e("进度回调=" + finalProgress);
                    Completable.fromAction(() -> callback.onProgress(finalProgress))
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe();
//                }
            });
            OSSAsyncTask<PutObjectResult> asyncTask = mOssClient.asyncPutObject(request, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    uploadSuceesOne(request, size, callback);
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                    AddCount();
                    //移除执行完毕的任务
                    mAsyncTaskMap.remove(request.getObjectKey());

                    if (mPutCount == size) {
                        //上传失败
                        for (Map.Entry<String, String> entry : mSuccessMap.entrySet()) {
                            String value = entry.getValue();
                            asyncDelete(value);
                        }
                        multiReset();
                        if (callback != null) {
                            Completable.fromAction(callback::onError)
                                    .subscribeOn(AndroidSchedulers.mainThread())
                                    .subscribe();
                        }
                    }
                }
            });

            mAsyncTaskMap.put(objectKey, asyncTask);
        }
    }

    private synchronized void uploadSuceesOne(PutObjectRequest request, int size, @Nullable OSSCallback callback) {
        mPutCount++;
        String requestObjectKey = request.getObjectKey();
        //移除执行完毕的任务
        mAsyncTaskMap.remove(requestObjectKey);
        String filePath = mPathInfoMap.get(requestObjectKey).path;

        mSuccessMap.put(filePath, requestObjectKey);
        LogUtil.e("requestObjectKey=" + requestObjectKey + "->filePath=" + filePath +" --> "+ mSuccessMap.size() +"  -- mPutCount " + mPutCount);
        if (mPutCount == size) {
            if (mSuccessMap.size() == size) {
                //全部上传成功
                fileSuccess(callback);
            } else {
                //部分上传成功
                for (Map.Entry<String, String> entry : mSuccessMap.entrySet()) {
                    String value = entry.getValue();
                    asyncDelete(value);
                }
                multiReset();
                if (callback != null) {
                    Completable.fromAction(callback::onError)
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe();
                }
            }
        }
    }

    private synchronized void fileSuccess(@Nullable OSSCallback callback) {
        if (callback != null) {
            Completable.fromAction(() -> callback.onSuccess())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe();
//                                if (callback instanceof OSSMultiImageCallback) {
//                                    callImagesCompleted((OSSMultiImageCallback) callback);
//                                } else if (callback instanceof OSSVideoCallback) {
//                                    callVideoCompleted(((OSSVideoCallback) callback));
//                                }
        }
        multiReset();
    }

    private String generateObjectKeyFromFile(File file) {
        return Constant.PRE_PATH + file.getName();
    }

//    private void callImagesCompleted(OSSMultiImageCallback callback) {
//        List<IllustrationsBean> list = new ArrayList<>();
//        for (Map.Entry<String, String> entry : mSuccessMap.entrySet()) {
//            String key = entry.getKey();
//            String value = entry.getValue();
//
//            IllustrationsBean bean = new IllustrationsBean();
//            bean.setObjectName(value);
//            int[] info = getImageWidthHeight(key);
//            bean.setWidth(info[0]);
//            bean.setHeight(info[1]);
//            bean.setIndex(mPathInfoMap.get(value).index);
//            list.add(bean);
//        }
//        Collections.sort(list);
//        Completable.fromAction(() -> callback.onSuccess(list))
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .subscribe();
//    }
//
//    private void callVideoCompleted(OSSVideoCallback callback) {
//        List<IllustrationsBean> list = new ArrayList<>();
//        VideoFileBean videoFileBean = new VideoFileBean();
//        for (Map.Entry<String, PathInfo> entry : mPathInfoMap.entrySet()) {
//            PathInfo value = entry.getValue();
//            if (value.index == 0) {
//                IllustrationsBean bean = new IllustrationsBean();
//                bean.setObjectName(entry.getKey());
//                int[] info = getImageWidthHeight(value.path);
//                bean.setWidth(info[0]);
//                bean.setHeight(info[1]);
//                list.add(bean);
//            } else {
//                videoFileBean.setObjectName(entry.getKey());
//                videoFileBean.setDuration(callback.getDuration());
//            }
//        }
//        Completable.fromAction(() -> callback.onSuccess(list, videoFileBean))
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .subscribe();
//    }

    public void asyncPutVideo(String imagePath, String videoPath, OSSVideoCallback callback) {
        List<String> pathList = new ArrayList<>();
        pathList.add(imagePath);
        pathList.add(videoPath);
        asyncMultiPut(pathList, callback);
    }

    public void asyncMultiPutImage(List<String> pathList, OSSCallback callback) {
        asyncMultiPut(pathList, callback);
    }

    public void cancelAllTask() {
        Iterator<Map.Entry<String, OSSAsyncTask>> iterator = mAsyncTaskMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, OSSAsyncTask> entry = iterator.next();
            OSSAsyncTask asyncTask = entry.getValue();
            asyncTask.cancel();
            iterator.remove();
        }
    }

    public boolean cancelTaskAndDelete(@NonNull String... paths) {
        for (String path : paths) {
            File file = new File(path);
            if (!file.exists()) {
                LogUtil.e("file Not exist");
                return false;
            }
            String objectKey = generateObjectKeyFromFile(file);
            OSSAsyncTask asyncTask = mAsyncTaskMap.get(objectKey);
            if (asyncTask != null) {
                asyncTask.cancel();
                mAsyncTaskMap.remove(objectKey);
            } else {
                asyncDelete(objectKey);
            }
        }

        return true;
    }

    private void multiReset() {
        mSuccessMap.clear();
        mPathInfoMap.clear();
        mProgressMap.clear();
        mPutCount = 0;
    }

    public static int[] getImageWidthHeight(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();

        /**
         * 最关键在此,把options.inJustDecodeBounds = true;
         * 这里再decodeFile(),返回的bitmap为空,但此时调用options.outHeight时,已经包含了图片的高了
         */
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options); // 此时返回的bitmap为null
        /**
         *options.outHeight为原始图片的高
         */
        return new int[]{options.outWidth, options.outHeight};
    }

    public interface OSSCallback {

        void onSuccess();

        default void onProgress(float progress) {

        }

        default void onError() {

        }
    }

    public interface OSSSingleCallback extends OSSCallback {
        void onSuccess(PutObjectRequest request, PutObjectResult result);
    }

    public interface OSSMultiImageCallback extends OSSCallback {
//        void onSuccess(List<IllustrationsBean> list);
    }

    public interface OSSVideoCallback extends OSSCallback {
//        void onSuccess(List<IllustrationsBean> list, VideoFileBean videoFileBean);

        int getDuration();
    }

    private class PathInfo {
        private int index;
        private String path;

        private PathInfo(int index, String path) {
            this.index = index;
            this.path = path;
        }
    }


}

 

第二个  

package utils;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.OSSLogToFileUtils;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.CompleteMultipartUploadResult;
import com.alibaba.sdk.android.oss.model.HeadObjectRequest;
import com.alibaba.sdk.android.oss.model.HeadObjectResult;
import com.alibaba.sdk.android.oss.model.ListObjectsRequest;
import com.alibaba.sdk.android.oss.model.ListObjectsResult;
import com.alibaba.sdk.android.oss.model.MultipartUploadRequest;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.File;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;

/**
 * Created by mOss on 2015/12/7 0007.
 * 支持普通上传,普通下载
 */
public class OssService {

    public OSS mOss;
    private String mBucket;
    private String mCallbackAddress;
    private static String mResumableObjectKey = "resumableObject";
    private Context mContext;

    public OssService( String bucket ,Context context,String endpoint) {
        this.mBucket = bucket;
        this.mContext = context;

        OSSCredentialProvider credentialProvider2 = new OSSPlainTextAKSKCredentialProvider("key", "key");

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
        mOss = new OSSClient(mContext, endpoint, credentialProvider2, conf);
        OSSLog.enableLog();
    }






    public void setBucketName(String bucket) {
        this.mBucket = bucket;
    }

    public void initOss(OSS _oss) {
        this.mOss = _oss;
    }

    public void setCallbackAddress(String callbackAddress) {
        this.mCallbackAddress = callbackAddress;
    }

//    public void asyncGetImage(String object) {
//
//        final long get_start = System.currentTimeMillis();
//        if ((object == null) || object.equals("")) {
//            Log.w("AsyncGetImage", "ObjectNull");
//            return;
//        }
//
//        GetObjectRequest get = new GetObjectRequest(mBucket, object);
//        get.setCRC64(OSSRequest.CRC64Config.YES);
//        get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
//            @Override
//            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
//                Log.d("GetObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
//                int progress = (int) (100 * currentSize / totalSize);
//                mDisplayer.updateProgress(progress);
//                mDisplayer.displayInfo("下载进度: " + String.valueOf(progress) + "%");
//            }
//        });
//        OSSAsyncTask task = mOss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
//            @Override
//            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
//                // 请求成功
//                InputStream inputStream = result.getObjectContent();
//                //Bitmap bm = BitmapFactory.decodeStream(inputStream);
//                try {
//                    //需要根据对应的View大小来自适应缩放
//                    Bitmap bm = mDisplayer.autoResizeFromStream(inputStream);
//                    long get_end = System.currentTimeMillis();
//                    OSSLog.logDebug("get cost: " + (get_end - get_start) / 1000f);
//                    mDisplayer.downloadComplete(bm);
//                    mDisplayer.displayInfo("Bucket: " + mBucket + "\nObject: " + request.getObjectKey() + "\nRequestId: " + result.getRequestId());
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
//                String info = "";
//                // 请求异常
//                if (clientExcepion != null) {
//                    // 本地异常如网络异常等
//                    clientExcepion.printStackTrace();
//                    info = clientExcepion.toString();
//                }
//                if (serviceException != null) {
//                    // 服务异常
//                    Log.e("ErrorCode", serviceException.getErrorCode());
//                    Log.e("RequestId", serviceException.getRequestId());
//                    Log.e("HostId", serviceException.getHostId());
//                    Log.e("RawMessage", serviceException.getRawMessage());
//                    info = serviceException.toString();
//                }
//                mDisplayer.downloadFail(info);
//                mDisplayer.displayInfo(info);
//            }
//        });
//    }

    /**
     * 服务器地址路径
     * @param object
     * @param localFile
     * @param uploadCallBack
     */
    public void asyncPutImage(String object, final String localFile, final UploadCallBack uploadCallBack) {
        final long upload_start = System.currentTimeMillis();

        if (object.equals("")) {
            Log.w("AsyncPutImage", "ObjectNull");
            return;
        }

        File file = new File(localFile);
        if (!file.exists()) {
            Log.w("AsyncPutImage", "FileNotExist");
            Log.w("LocalFile", localFile);
            return;
        }


        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(mBucket, object, localFile);
        put.setCRC64(OSSRequest.CRC64Config.YES);
//        if (mCallbackAddress != null) {
//            // 传入对应的上传回调参数,这里默认使用OSS提供的公共测试回调服务器地址
//            put.setCallbackParam(new HashMap<String, String>() {
//                {
//                    put("callbackUrl", mCallbackAddress);
//                    //callbackBody可以自定义传入的信息
//                    put("callbackBody", "filename=${object}");
//                }
//            });
//        }

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (100 * currentSize / totalSize);

            }
        });

        OSSAsyncTask task = mOss.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());

                long upload_end = System.currentTimeMillis();
                OSSLog.logDebug("upload cost: " + (upload_end - upload_start) / 1000f);
                uploadCallBack.uploadSuccess(localFile);
                Log.e("uploadCallBack--- OK ", localFile);

            }

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


    /*private void asyncMultiPut(@NonNull List<String> pathList, @Nullable OSSCallback callback) {
        multiReset();
        final int size = pathList.size();
        for (int i = 0; i < size; i++) {
            String path = pathList.get(i);
            File file = new File(path);
            if (!file.exists()) {
                Timber.tag(TAG).e("file Not exist");
                return;
            }
            String objectKey = generateObjectKeyFromFile(file);
            mPathInfoMap.put(objectKey, new PathInfo(i, path));

            PutObjectRequest request = new PutObjectRequest(OssConfig.bucket, objectKey, file.getPath());
            request.setProgressCallback((request1, currentSize, totalSize) -> {
                mProgressMap.put(request1.getObjectKey(), new long[]{currentSize, totalSize});
                if (callback != null && mProgressMap.size() == size) {
                    long current = 0, total = 0;
                    for (Map.Entry<String, long[]> entry : mProgressMap.entrySet()) {
                        long[] value = entry.getValue();
                        current += value[0];
                        total += value[1];
                    }
                    float progress = current * 1.0f / total * 1.0f;
                    if (progress > 1) {
                        progress = 1;
                    }
                    final float finalProgress = progress;
                    Timber.tag(TAG).d("进度回调=" + finalProgress);
                    Completable.fromAction(() -> callback.onProgress(finalProgress))
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe();
                }
            });
            OSSAsyncTask<PutObjectResult> asyncTask = mOssClient.asyncPutObject(request, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    mPutCount++;
                    String requestObjectKey = request.getObjectKey();

                    //移除执行完毕的任务
                    mAsyncTaskMap.remove(requestObjectKey);

                    String filePath = mPathInfoMap.get(requestObjectKey).path;
                    Timber.tag(TAG).d("requestObjectKey=" + requestObjectKey + "->filePath=" + filePath);
                    mSuccessMap.put(filePath, requestObjectKey);

                    if (mPutCount == size) {
                        if (mSuccessMap.size() == size) {
                            //全部上传成功
                            if (callback != null) {
                                if (callback instanceof OSSMultiImageCallback) {
                                    callImagesCompleted((OSSMultiImageCallback) callback);
                                } else if (callback instanceof OSSVideoCallback) {
                                    callVideoCompleted(((OSSVideoCallback) callback));
                                }
                            }
                            multiReset();
                        } else {
                            //部分上传成功
                            for (Map.Entry<String, String> entry : mSuccessMap.entrySet()) {
                                String value = entry.getValue();
                                asyncDelete(value);
                            }
                            multiReset();
                            if (callback != null) {
                                Completable.fromAction(callback::onError)
                                        .subscribeOn(AndroidSchedulers.mainThread())
                                        .subscribe();
                            }
                        }
                    }
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                    mPutCount++;
                    //移除执行完毕的任务
                    mAsyncTaskMap.remove(request.getObjectKey());

                    if (mPutCount == size) {
                        //上传失败
                        for (Map.Entry<String, String> entry : mSuccessMap.entrySet()) {
                            String value = entry.getValue();
                            asyncDelete(value);
                        }
                        multiReset();
                        if (callback != null) {
                            Completable.fromAction(callback::onError)
                                    .subscribeOn(AndroidSchedulers.mainThread())
                                    .subscribe();
                        }
                    }
                }
            });

            mAsyncTaskMap.put(objectKey, asyncTask);
        }
    }*/

    // Downloads the files with specified prefix in the asynchronous way.
    public void asyncListObjectsWithBucketName() {
        ListObjectsRequest listObjects = new ListObjectsRequest(mBucket);
        // Sets the prefix
        listObjects.setPrefix("android");
        listObjects.setDelimiter("/");
        // Sets the success and failure callback. calls the Async API
        OSSAsyncTask task = mOss.asyncListObjects(listObjects, new OSSCompletedCallback<ListObjectsRequest, ListObjectsResult>() {
            @Override
            public void onSuccess(ListObjectsRequest request, ListObjectsResult result) {
                String info = "";
                OSSLog.logDebug("AyncListObjects", "Success!");
                for (int i = 0; i < result.getObjectSummaries().size(); i++) {
                    info += "\n" + String.format("object: %s %s %s", result.getObjectSummaries().get(i).getKey(), result.getObjectSummaries().get(i).getETag(), result.getObjectSummaries().get(i).getLastModified().toString());
                    OSSLog.logDebug("AyncListObjects", info);
                }

            }

            @Override
            public void onFailure(ListObjectsRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // request exception
                if (clientExcepion != null) {
                    // client side exception such as network exception
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // service side exception.
                    OSSLog.logError("ErrorCode", serviceException.getErrorCode());
                    OSSLog.logError("RequestId", serviceException.getRequestId());
                    OSSLog.logError("HostId", serviceException.getHostId());
                    OSSLog.logError("RawMessage", serviceException.getRawMessage());
                }

            }
        });
    }

    // Gets file's metadata
    public void headObject(String objectKey) {
        // Creates a request to get the file's metadata
        HeadObjectRequest head = new HeadObjectRequest(mBucket, objectKey);

        OSSAsyncTask task = mOss.asyncHeadObject(head, new OSSCompletedCallback<HeadObjectRequest, HeadObjectResult>() {
            @Override
            public void onSuccess(HeadObjectRequest request, HeadObjectResult result) {
                OSSLog.logDebug("headObject", "object Size: " + result.getMetadata().getContentLength());
                OSSLog.logDebug("headObject", "object Content Type: " + result.getMetadata().getContentType());


            }

            @Override
            public void onFailure(HeadObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // request exception
                if (clientExcepion != null) {
                    // client side exception,  such as network exception
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // service side exception
                    OSSLog.logError("ErrorCode", serviceException.getErrorCode());
                    OSSLog.logError("RequestId", serviceException.getRequestId());
                    OSSLog.logError("HostId", serviceException.getHostId());
                    OSSLog.logError("RawMessage", serviceException.getRawMessage());
                }

            }
        });
    }

    public void asyncMultipartUpload(String uploadKey, String uploadFilePath) {
        MultipartUploadRequest request = new MultipartUploadRequest(mBucket, uploadKey,
                uploadFilePath);
        request.setCRC64(OSSRequest.CRC64Config.YES);
        request.setProgressCallback(new OSSProgressCallback<MultipartUploadRequest>() {

            @Override
            public void onProgress(MultipartUploadRequest request, long currentSize, long totalSize) {
                OSSLog.logDebug("[testMultipartUpload] - " + currentSize + " " + totalSize, false);
            }
        });
        mOss.asyncMultipartUpload(request, new OSSCompletedCallback<MultipartUploadRequest, CompleteMultipartUploadResult>() {
            @Override
            public void onSuccess(MultipartUploadRequest request, CompleteMultipartUploadResult result) {

            }

            @Override
            public void onFailure(MultipartUploadRequest request, ClientException clientException, ServiceException serviceException) {
                if (clientException != null) {

                } else if (serviceException != null) {

                }

            }
        });
    }


    public interface UploadCallBack {
        void uploadSuccess(String result);

        void onError();
    }
}

完整路径  例如 : 

http://bucket.oss-cn-beijing.aliyuncs.com/hk/1236446565.jpg

路径包括 二部分 ,一部分 基路径   http://bucket.oss-cn-beijing.aliyuncs.com/ 是服务器申请后阿里给的 

第二部分 是文件路径 hk/1236446565.jpg 可以按业务关系 自己拼接 。(一般是文件路径+ 文件名称) 。

1.PutObjectRequest request = new PutObjectRequest(Constant.BUCKET, objectKey, file.getPath()); 

objectkey 是生成的网络路径 子路径 ,就是子路径 。

bucket 就是 基路径中 的 oss 前面的 

第三个参数 是本地文件的绝对路径 

2. ENDPOINT 是指定的阿里服务器地址,有北京 上海 杭州 等,申请成功后,在后台页面会给出。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值