当前位置: 首页>后端>正文

Android Amazon S3 功能接入

一、前言:

前段时间项目需求需要接入亚马逊的S3云服务存储视频、图片资源,但是发现网上关于Android 端Amazon S3的资料写的都不是特别充足,于是专门写一篇给需要接入此功能的作为参考。

官方文档:
官方JAVA文档:
官方Kotlin文档:

二、接入

1、导包

//亚马逊sdk 2.6.10
implementation "com.amazonaws:aws-android-sdk-s3:2.16.+"
implementation ("com.amazonaws:aws-android-sdk-mobile-client:2.16.+") { transitive = true }

2、Application中初始化SDK


    //亚马逊客户端对象
    public static AmazonS3Client s3Client;
   /**
     * 初始化亚马逊SDK
     */
    private static void initAMS() {
        //亚马逊的key
        String accessKey = "XXXXXX";
        String secretKey = "XXXXXX";
        if (s3Client==null){
            // 初始化S3客户端
            BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
            s3Client = new AmazonS3Client(credentials);
            s3Client.setRegion(Region.getRegion(Regions.US_EAST_1));
        }
    }

3、上传图片封装1:

           //上传的地址
            String path = file.getAbsolutePath();
            MyToash.Log("lyy","----返回地址:"+path);
            // 设置上传的键(Key),即文件名
            String myKey = OSSUploadUtils.INSTANCE.createPicName(1);
            //上传到亚马逊
            AmazonUtil.INSTANCE.uploadAmazonUtil(myKey,path, new Function2<Boolean, String, Unit>() {
                @Override
                public Unit invoke(Boolean aBoolean, String url) {
                    if (aBoolean){
                        //上传成功 https://novelbucket.s3.amazonaws.com/avatar/1687950332356.png
                    }else{
                        //上传失败
                        MyToash.Toash(activity,result);
                    }
                    return null;
                }
            });
  /**
     * 生成图片名称
     * type:1:头像;2:意见反馈
     */
    fun createPicName(type:Int):String{
        var picName = ""
            //图片名称
        if (type==1){
            //头像
            picName = "avatar/${System.currentTimeMillis()}.png"
        }else{
            //意见反馈
            picName = "feedback/${System.currentTimeMillis()}.png"
        }
        return picName
    }

4、上传图片封装2:

object  AmazonUtil {
    //协程
    val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    /**
     * 初始化亚马逊
     */
    fun uploadAmazonUtil(myKey:String,loaclPath:String,result: (Boolean,String)->Unit){

        try {
            scope.launch(Dispatchers.IO) {
                //调用上传
                S3Uploader.uploadImage(loaclPath, myKey,object : UploadCallback {
                    override fun onSuccess(imageUrl: String) {
                        // 上传成功后的处理逻辑
                        result.invoke(true,imageUrl)
                        MyToash.Log("lyy","上传图片----imageUrl:${imageUrl}")
                    }

                    override fun onFailure(e: Exception) {
                        // 上传失败后的处理逻辑
                        result.invoke(false,"error:${e.toString()}")
                        MyToash.Log("lyy","上传图片----失败:${e.toString()}")
                    }
                })
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}

4、上传图片封装3:

public class S3Uploader {
    private static final String BUCKET_NAME = "xxxbucket";

    public interface UploadCallback {
        void onSuccess(String imageUrl);
        void onFailure(Exception e);
    }

    /**
     *
     * @param imagePath
     * @param key 的样式是:"image.jpg"也就是文件名
     * @param callback
     */
    public static void uploadImage(String imagePath,String key, final UploadCallback callback) {
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, new File(imagePath));
            // 设置文件的ACL为公共读取
            putObjectRequest.setCannedAcl(CannedAccessControlList.PublicReadWrite);
            //上传
            s3Client.putObject(putObjectRequest);

            // 设置 URL 的过期时间为 1 小时
            Date expiration = new Date(currentTimeMillis() + 3600000);
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, key)
                    .withMethod(HttpMethod.POST)
                    .withExpiration(expiration);
            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
            //https://novelbucket.s3.amazonaws.com/avatar/1687950332356.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230628T110534Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3599&X-Amz-Credential=AKIAZK6Y2B545PDIBYFG%2F20230628%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=ebc2fec48672c9d14416ebd7f2bc517baa4e03087fa801b66b1b7d1924a4615f
            //截取图片的url
            String imageUrl = url.toString();
            int index = imageUrl.indexOf("?");
            String newUrl = imageUrl.substring(0,index);
            callback.onSuccess(newUrl);
        } catch (AmazonServiceException e) {
            e.printStackTrace();
            callback.onFailure(e);
        } catch (AmazonClientException e) {
            e.printStackTrace();
            callback.onFailure(e);
        }
    }
}

继承以上,就可以上传文件或者图片就会成功,返回成功的地址。


https://www.xamrdz.com/backend/3r51941838.html

相关文章: