亚马逊S3/AmazonS3-上传/下载图片

implementation 'com.amazonaws:aws-android-sdk-s3:2.16.+'

 /**
     * 亚马逊s3 上传/下载图片
     *
     * @param key 图片存储的名称
     */
    public void downloadFileByKey(String key) throws JSONException {
        JSONObject jsonConfig = new JSONObject();
        JSONObject s3TransferUtility = new JSONObject();
        jsonConfig.putOpt("S3TransferUtility", s3TransferUtility);
        s3TransferUtility.put("Region", "服务端请求来的region");
        s3TransferUtility.put("Bucket", "服务端请求来bucket");
        AWSSessionCredentials credentials = new AWSSessionCredentials() {
            @Override
            public String getSessionToken() {
                return "服务端请求过来的SessionToken";
            }

            @Override
            public String getAWSAccessKeyId() {
                return "服务端请求来的AccessKey";
            }

            @Override
            public String getAWSSecretKey() {
                return "服务端请求来的SecretKey";
            }
        };
        //如果认证信息存在本地,使用这个
       /* AWSCredentials credentials = new AWSCredentials() {
            @Override
            public String getAWSAccessKeyId() {
                return "AKIAQXAC4WLGU2Q4YWMA";
            }

            @Override
            public String getAWSSecretKey() {
                return "JYzHJbY6DxB/QaGW+uaAZCYbGYgRsa4jPbQNYIGv";
            }
        };*/

        AWSConfiguration configuration = new AWSConfiguration(jsonConfig);
        TransferUtility utility = TransferUtility.builder()
                .context(this)
                .s3Client(new AmazonS3Client(credentials))
                .awsConfiguration(configuration)
                .build();

        //下载图片
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/test44.png");
        TransferObserver observer = utility.download(key, file);

        //上传文件   path 上传文件的地址
        // TransferObserver observer = utility.upload(key, new File(path));
        observer.setTransferListener(new TransferListener() {
            @Override
            public void onStateChanged(int i, TransferState transferState) {
                if (transferState == TransferState.COMPLETED) {
                    //下载完成了
                }
            }

            @Override
            public void onProgressChanged(int i, long l, long l1) {
            }

            @Override
            public void onError(int i, Exception e) {
            }
        });
    }

你可能感兴趣的:(亚马逊S3/AmazonS3-上传/下载图片)