Android OSS下载文件

本文介绍如何在Android应用中使用阿里云OSS下载文件,涉及依赖安装、Config配置、OSS初始化和下载操作的详细步骤,以及处理可能遇到的错误和进度跟踪。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近期,公司要求使用OSS下载文件,优化下载模块
首先,想要使用OSS,必须下载其相关依赖

    implementation 'com.aliyun.dpa:oss-android-sdk:2.9.5'
   // implementation project(':oss-android-sdk')

依赖下载成功后,需要配置Config文件(提高安全性,使用STS方式)

public class Config {

    // 访问的endpoint地址
    public static final String OSS_ENDPOINT = "后台获取的end_point地址";
    //callback 测试地址
    public static final String OSS_CALLBACK_URL = "上传的callback";
   
    public static final String STS_SERVER_URL = "后台获取STS地址";//STS 地址

    public static final String BUCKET_NAME = "后台提供的Bucket_name";
    public static final String OSS_ACCESS_KEY_ID = "后台提供的AccessKeyID";
    public static final String OSS_ACCESS_KEY_SECRET = "后台提供的AccessKeySecret";

    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;
    public static final int REQUESTCODE_OPEN_DOCUMENT = 10113;
}

在我们配置好Config文件后,就可以初始化OSS了:

 OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
       	credentialProvider = new OSSAuthCredentialsProvider(Config.STS_SERVER_URL);
       	editBucketName = Config.BUCKET_NAME;
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
        OSSLog.enableLog();		//开启Log打印
        return new OssService(oss, editBucketName, displayer);

初始化完成后,就可以进行下载啦:

		GetObjectRequest get = new GetObjectRequest(Config.BUCKET_NAME, 下载的文件路径);
		//此处为设置进度条,如不需要可以删除
        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) + "%");
            }
        });
        OSSLog.logDebug("asyncGetObject");
        // 此处下载任务
        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);
            }
        });
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(); } }); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kstar_Ming_闫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值