本节介绍如何快速使用 OSS Android SDK 完成常见操作,如创建存储空间、上传文件、下载文件等。

本工程的更多用法请参考以下两种方式:

  • 查看 sample 目录(包含上传本地文件、下载文件、断点续传、设置回调等示例),详情请点击查看
  • 直接 git clone 工程
运行本工程前,您需要配置必要参数 Config,配置 Config 示例代码如下:
public class Config {

    // To run the sample correctly, the following variables must have valid values.
    // The endpoint value below is just the example. Please use proper value according to your region

    // 访问的endpoint地址
    public static final String OSS_ENDPOINT = "http://oss-cn-shanghai.aliyuncs.com";
    //callback 测试地址
    public static final String OSS_CALLBACK_URL = "http://oss-demo.aliyuncs.com:23450";
    // STS 鉴权服务器地址。
    // 或者根据工程sts_local_server目录中本地鉴权服务脚本代码启动本地STS鉴权服务器。
    public static final String STS_SERVER_URL = "http://****/sts/getsts";//STS 地址

    public static final String BUCKET_NAME = "请输入bucket名称";
    public static final String OSS_ACCESS_KEY_ID = "<yourAccessKeyId>";;
    public static final String OSS_ACCESS_KEY_SECRET = "<yourAccessKeySecret>";

    public static final int DOWNLOAD_SUC = 1;
    public static final int DOWNLOAD_Fail = 2;
    public static final int UPLOAD_SUC = 3;
    public static final int UPLOAD_Fail = 4;
    public static final int UPLOAD_PROGRESS = 5;
    public static final int LIST_SUC = 6;
    public static final int HEAD_SUC = 7;
    public static final int RESUMABLE_SUC = 8;
    public static final int SIGN_SUC = 9;
    public static final int BUCKET_SUC = 10;
    public static final int GET_STS_SUC = 11;
    public static final int MULTIPART_SUC = 12;
    public static final int STS_TOKEN_SUC = 13;
    public static final int FAIL = 9999;
    public static final int REQUESTCODE_AUTH = 10111;
    public static final int REQUESTCODE_LOCALPHOTOS = 10112;
}
说明
运行工程 demo 如下:

创建存储空间

存储空间是OSS全局命名空间,相当于数据的容器,可以存储若干文件。 以下代码用于新建一个存储空间:

CreateBucketRequest createBucketRequest = new CreateBucketRequest("<bucketName>");
// 设置存储空间的访问权限为公共读,默认为私有读写。
createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead); 
// 指定存储空间所在的地域。
createBucketRequest.setLocationConstraint("oss-cn-hangzhou");
OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
    @Override
    public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
        Log.d("locationConstraint", request.getLocationConstraint());
        }
    @Override
    public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
        // 请求异常。
        if (clientException != null) {
            // 本地异常,如网络异常等。
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // 服务异常。
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

存储空间的命名规范,请参见基本概念中的命名规范。创建存储空间详情,请参见创建存储空间

获取endpoint信息,请参见访问域名和数据中心文档。

上传文件

以下代码用于将指定的本地文件上传到OSS:

// 构造上传请求。
PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectName>", "<uploadFilePath>");

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

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

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // 请求异常。
        if (clientExcepion != null) {
            // 本地异常,如网络异常等。
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // 服务异常。
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// task.cancel(); // 可以取消任务。
// task.waitUntilFinished(); // 等待上传完成。

下载指定文件

以下代码用于将指定的OSS文件下载到本地文件:

// 构造下载文件请求。
GetObjectRequest get = new GetObjectRequest("<bucketName>", "<objectName>");

OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
    @Override
    public void onSuccess(GetObjectRequest request, GetObjectResult result) {
        // 请求成功。
        Log.d("asyncGetObject", "DownloadSuccess");
        Log.d("Content-Length", "" + result.getContentLength());

        InputStream inputStream = result.getObjectContent();
        byte[] buffer = new byte[2048];
        int len;

        try {
            while ((len = inputStream.read(buffer)) != -1) {
                // 您可以在此处编写代码来处理下载的数据。
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    // GetObject请求成功,将返回GetObjectResult,其持有一个输入流的实例。返回的输入流,请自行处理。
    public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // 请求异常。
        if (clientExcepion != null) {
            // 本地异常,如网络异常等。
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // 服务异常。
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

// task.cancel(); // 可以取消任务。
// task.waitUntilFinished(); // 等待任务完成。
说明 返回数据的输入流需自行处理。