Android は Amazon s3 ストレージに接続してアップロード ファイルのヘッダー情報を設定し、ファイルを直接ダウンロードできます

プロジェクト build.gradle に構成を追加します。

implementation "com.amazonaws:aws-android-sdk-s3:2.22.1"
implementation ("com.amazonaws:aws-android-sdk-mobile-client:2.22.1") { transitive = true }

新しい Util クラスを作成します。

public class Util {
    private static final String TAG = Util.class.getSimpleName();

    private static AmazonS3Client sS3Client;
    private static AWSCredentialsProvider sMobileClient;
    private static TransferUtility sTransferUtility;

    /**
     * Gets an instance of AWSMobileClient which is
     * constructed using the given Context.
     *
     * @param context Android context
     * @return AWSMobileClient which is a credentials provider
     */
    private static AWSCredentialsProvider getCredProvider(Context context) {
        if (sMobileClient == null) {
            final CountDownLatch latch = new CountDownLatch(1);
            AWSMobileClient.getInstance().initialize(context, new Callback<UserStateDetails>() {
                @Override
                public void onResult(UserStateDetails result) {
                    latch.countDown();
                }

                @Override
                public void onError(Exception e) {
                    latch.countDown();
                }
            });
            try {
                latch.await();
                sMobileClient = AWSMobileClient.getInstance();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return sMobileClient;
    }

    /**
     * Gets an instance of a S3 client which is constructed using the given
     * Context.
     *
     * @param context Android context
     * @return A default S3 client.
     */
    public static AmazonS3Client getS3Client(Context context) {
        if (sS3Client == null) {
            try {
                String regionString = new AWSConfiguration(context)
                        .optJsonObject("S3TransferUtility")
                        .getString("Region");
                Region region = Region.getRegion(regionString);
                sS3Client = new AmazonS3Client(getCredProvider(context), region);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return sS3Client;
    }

    /**
     * Gets an instance of the TransferUtility which is constructed using the
     * given Context
     *
     * @param context Android context
     * @return a TransferUtility instance
     */
    public static TransferUtility getTransferUtility(Context context) {
        if (sTransferUtility == null) {
            sTransferUtility = TransferUtility.builder()
                    .context(context)
                    .s3Client(getS3Client(context))
                    .awsConfiguration(new AWSConfiguration(context))
                    .build();
        }

        return sTransferUtility;
    }

    /**
     * Converts number of bytes into proper scale.
     *
     * @param bytes number of bytes to be converted.
     * @return A string that represents the bytes in a proper scale.
     */
    public String getBytesString(long bytes) {
        String[] quantifiers = new String[]{
                "KB", "MB", "GB", "TB"
        };
        double speedNum = bytes;
        for (int i = 0; ; i++) {
            if (i >= quantifiers.length) {
                return "";
            }
            speedNum /= 1024;
            if (speedNum < 512) {
                return String.format(Locale.US, "%.2f", speedNum) + " " + quantifiers[i];
            }
        }
    }
}

アクティビティの onCreate メソッドで TransferUtility オブジェクトを取得します。

TransferUtility transferUtility = Util.getTransferUtility(this);

ヘッダー情報を設定するためのメインコードは次のとおりです。

if (metadata == null) {
    metadata = new ObjectMetadata();
    metadata.setContentType(MIMETYPE_OCTET_STREAM);//设置头部信息
}

完全なコードは次のとおりです

private void upload(File file, String awsFilePath) {
    if (metadata == null) {
        metadata = new ObjectMetadata();
        metadata.setContentType(MIMETYPE_OCTET_STREAM);//设置头部信息
    }
    TransferObserver observer = transferUtility.upload(
            awsFilePath,
            file,
            metadata
    );
    observer.setTransferListener(new UploadListener(new OnUploadListener() {
        @Override
        public void onStateChanged(int id, TransferState newState) {
                
        }

        @Override
        public void onError(int id, Exception e) {
            
        }
    }));
}
public class UploadListener implements TransferListener {

    private final OnUploadListener mOnUploadListener;

    public UploadListener(OnUploadListener listener) {
        mOnUploadListener = listener;
    }

    // Simply updates the UI list when notified.
    @Override
    public void onError(int id, Exception e) {
        if (mOnUploadListener != null) {
            mOnUploadListener.onError(id, e);
        }
    }

    @Override
    public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
    }

    @Override
    public void onStateChanged(int id, TransferState newState) {
        if (newState == TransferState.COMPLETED) {
            if (mOnUploadListener != null) {
                mOnUploadListener.onStateChanged(id, newState);
            }
        }
    }
}
public interface OnUploadListener {

    void onStateChanged(int id, TransferState newState);

    void onError(int id, Exception e);
}

 

おすすめ

転載: blog.csdn.net/CHEN_ZL0125/article/details/114888490
おすすめ