如果要下载的文件太大,或者一次性下载耗时太长,您可以通过流式下载,一次处理部分内容,直到完成文件的下载。

下载指定文件后将获得文件的输入流,此操作要求用户对该Object有读权限。

同步调用:

//构造下载文件请求
//objectKey等同于objectName,表示从OSS下载文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg
GetObjectRequest get = new GetObjectRequest("<bucketName>", "<objectKey>");

//设置下载进度回调
get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
            @Override
            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                OSSLog.logDebug("getobj_progress: " + currentSize+"  total_size: " + totalSize, false);
            }
        });

try {
    // 同步执行下载请求,返回结果
    GetObjectResult getResult = oss.getObject(get);

    Log.d("Content-Length", "" + getResult.getContentLength());

    // 获取文件输入流
    InputStream inputStream = getResult.getObjectContent();

    byte[] buffer = new byte[2048];
    int len;

    while ((len = inputStream.read(buffer)) != -1) {
        // 处理下载的数据,比如图片展示或者写入文件等
    }

    // 下载后可以查看文件元信息
    ObjectMetadata metadata = getResult.getMetadata();
    Log.d("ContentType", metadata.getContentType());


} catch (ClientException e) {
    // 本地异常如网络异常等
    e.printStackTrace();
} catch (ServiceException e) {
    // 服务异常
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
} catch (IOException e) {
    e.printStackTrace();
}

异步调用:

GetObjectRequest get = new GetObjectRequest("<bucketName>", "<objectKey>");
//设置下载进度回调
get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
            @Override
            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                OSSLog.logDebug("getobj_progress: " + currentSize+"  total_size: " + totalSize, false);
            }
        });
OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
    @Override
    public void onSuccess(GetObjectRequest request, GetObjectResult result) {
        // 请求成功
        InputStream inputStream = result.getObjectContent();

        byte[] buffer = new byte[2048];
        int len;

        try {
            while ((len = inputStream.read(buffer)) != -1) {
                // 处理下载的数据
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    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());
        }
    }
});