Android使用阿里云OSS存储文件上传

build.gradle

中添加依赖

implementation 'com.aliyun.dpa:oss-android-sdk:+'

Config.java

/**
 * Config
 *
 * @author lao
 * @date 2019/10/8
 */
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-shenzhen.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 = "talkp";
    public static final String OSS_ACCESS_KEY_ID = "仓库ID";
    public static final String OSS_ACCESS_KEY_SECRET = "秘钥";

    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;
}

 

 

UploadHelper.java

public class UploadHelper {
    private static final String TAG = UploadHelper.class.getSimpleName();
    // 与你们的存储区域有关系
    public static final String ENDPOINT = "oss-cn-shenzhen.aliyuncs.com";
    // 上传的仓库名
    private static final String BUCKET_NAME = "talkp";


    private static OSS getClient() {

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // connction time out default 15s
        conf.setSocketTimeout(15 * 1000); // socket timeout,default 15s
        conf.setMaxConcurrentRequest(5); // synchronous request number,default 5
        conf.setMaxErrorRetry(2); // retry,default 2
        OSSLog.enableLog(); //write local log file ,path is SDCard_path\OSSLog\logs.csv

        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET, "<StsToken.SecurityToken>");
        OSSPlainTextAKSKCredentialProvider provider = new OSSPlainTextAKSKCredentialProvider(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET);

        OSS oss = new OSSClient(Factory.app(), Config.OSS_ENDPOINT, provider, conf);
        // 明文设置secret的方式建议只在测试时使用,更多鉴权模式请参考后面的`访问控制`章节
        return oss;
    }


    /**
     * 上传的最终方法,成功返回则一个路径
     *
     * @param objKey 上传上去后,在服务器上的独立的KEY
     * @param path   需要上传的文件的路径
     * @return 存储的地址
     */
    private static String upload(String objKey, String path) {
        // 构造一个上传请求
        PutObjectRequest request = new PutObjectRequest(BUCKET_NAME,
                objKey, path);

        try {
            // 初始化上传的Client
            OSS client = getClient();
            // 开始同步上传
            PutObjectResult result = client.putObject(request);
            Log.d(TAG, "upload: result=" + result);
            // 得到一个外网可访问的地址
            String url = client.presignPublicObjectURL(BUCKET_NAME, objKey);
            // 格式打印输出
            Log.d(TAG, String.format("PublicObjectURL:%s", url));
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            // 如果有异常则返回空
            return null;
        }
    }

    /**
     * 上传普通图片
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadImage(String path) {
        String key = getImageObjKey(path);
        return upload(key, path);
    }

    /**
     * 上传头像
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadPortrait(String path) {
        String key = getPortraitObjKey(path);
        return upload(key, path);
    }

    /**
     * 上传音频
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadAudio(String path) {
        String key = getAudioObjKey(path);
        return upload(key, path);
    }

    /**
     * 分月存储,避免一个文件夹太多
     *
     * @return yyyyMM
     */
    private static String getDateString() {
        return DateFormat.format("yyyyMM", new Date()).toString();
    }

    // image/201703/dawewqfas243rfawr234.jpg
    private static String getImageObjKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("image/%s/%s.jpg", dateString, fileMd5);
    }

    // portrait/201703/dawewqfas243rfawr234.jpg
    private static String getPortraitObjKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("portrait/%s/%s.jpg", dateString, fileMd5);
    }

    // audio/201703/dawewqfas243rfawr234.mp3
    private static String getAudioObjKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("audio/%s/%s.mp3", dateString, fileMd5);
    }
}

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
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(); } }); } }
你可以使用阿里云官方提供的 OSS(对象存储服务)SDK 来实现 Android 上的文件上传功能。以下是一个简单的示例代码,需要先引入阿里云 OSS SDK 的依赖: ```java implementation 'com.aliyun.dpa:oss-android-sdk:3.1.8' ``` 然后,在你的代码中使用以下方法来实现文件上传: ```java import com.aliyun.dpa.oss.app.AppServiceFactory; import com.aliyun.dpa.oss.app.OSSClientFactory; import com.aliyun.dpa.oss.app.RunningConfig; import com.aliyun.dpa.oss.app.ServiceFactory; import com.aliyun.dpa.oss.app.UploadConfiguration; import com.aliyun.dpa.oss.app.UploadConfigurationFactory; import com.aliyun.dpa.oss.app.UploadManager; import com.aliyun.dpa.oss.app.util.FileUtil; import com.aliyun.dpa.oss.app.util.StringUtil; import com.aliyun.dpa.oss.app.util.UIUtil; import com.aliyun.dpa.oss.callback.ResultCallback; import com.aliyun.dpa.oss.model.OSSUploadConfiguration; import com.aliyun.dpa.oss.task.PutObjectTask; import com.aliyun.dpa.oss.task.TaskCancelledException; public class AliOSSUploader { private static final String ENDPOINT = "your_oss_endpoint"; // 你的 OSS Endpoint private static final String ACCESS_KEY_ID = "your_access_key_id"; // 你的 Access Key ID private static final String ACCESS_KEY_SECRET = "your_access_key_secret"; // 你的 Access Key Secret private static final String BUCKET_NAME = "your_bucket_name"; // 你的 Bucket 名称 public void uploadFile(String filePath) { // 创建 OSS 客户端 RunningConfig runningConfig = new RunningConfig(ACCESS_KEY_ID, ACCESS_KEY_SECRET, ENDPOINT); AppServiceFactory.init(runningConfig); ServiceFactory serviceFactory = OSSClientFactory.createServiceFactory(); UploadConfiguration configuration = UploadConfigurationFactory.getUploadConfiguration(); UploadManager uploadManager = serviceFactory.createUploadManager(configuration); // 构造上传任务 PutObjectTask putObjectTask = new PutObjectTask(BUCKET_NAME, StringUtil.generateRandomKey(), filePath); // 设置上传结果回调 putObjectTask.setResultCallback(new ResultCallback() { @Override public void onSuccess(Object object) { // 文件上传成功 UIUtil.showToast("文件上传成功"); } @Override public void onFailure(Exception e) { // 文件上传失败 UIUtil.showToast("文件上传失败:" + e.getMessage()); } @Override public void onProgress(Object object, long currentSize, long totalSize) { // 文件上传进度 int progress = (int) (currentSize * 100 / totalSize); UIUtil.showToast("文件上传进度:" + progress + "%"); } @Override public void onCancel(Object object) { // 文件上传取消 UIUtil.showToast("文件上传取消"); } }); // 开始上传任务 try { uploadManager.upload(putObjectTask); } catch (TaskCancelledException e) { // 上传任务取消 UIUtil.showToast("文件上传取消"); } } } ``` 以上代码中的 `your_oss_endpoint`、`your_access_key_id`、`your_access_key_secret` 和 `your_bucket_name` 分别是你的 OSS Endpoint、Access Key ID、Access Key Secret 和 Bucket 名称。你需要将它们替换为你自己的实际值。 调用 `uploadFile` 方法并传入要上传的文件路径,即可实现文件上传阿里云 OSS。记得在 AndroidManifest.xml 中添加网络权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 希望对你有帮助!如有其他问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值