看了很多篇亚马逊s3上传文件的文章,发现大多写的都不是很详细,不能正常运行的,很苦恼;于是就有了这次记录,让你不走弯路。
1.首先需要让运维申请账号和秘钥 创建bucket,你所有的上传的文件都在bucket这个文件下
2.初始化上传凭证
AWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey)
3.初始化S3 Client
setAccelerateModeEnabled 这个参数是设置bucket是否加速,如果运维没有开启加速一定要设置false,不然会报错
S3ClientOptions clientOptions = S3ClientOptions.builder().setAccelerateModeEnabled(false ).build()
AmazonS3Client uploadClient = new AmazonS3Client(awsCreds)
uploadClient.setS3ClientOptions(clientOptions)
4.获取上传管理类TransferUtility
transferUtility = TransferUtility.builder ().s3Client (uploadClient).context (context).build ();
5.上传文件file
关于:transferUtility.upload(bucketName, getFileKey(), uploadFiles)
bucketName:bucket运维在s3后台创建的提供
getFileKey():在s3后台的文件名称,比如 log/202001/test.zip
uploadFiles:上传的文件
public TransferObserver upload (String bucket, String key, File file)
TransferObserver transferObserver = transferUtility.upload(bucketName, getFileKey(), uploadFiles);
transferObserver.setTransferListener(new TransferListener () {
@Override
public void onStateChanged (int id, TransferState state) {
if (uploadMonitor != null ) {
if (state == TransferState.COMPLETED) {
uploadMonitor.onSuccess("file path == " + getSignUrl() + " " );
} else if (state == TransferState.FAILED) {
uploadMonitor.onFail("" );
} else if (state == TransferState.CANCELED) {
uploadMonitor.onFail("取消了" );
uploadId = -1 ;
@Override
public void onProgressChanged (int id, long bytesCurrent, long bytesTotal) {
DTLog.d("UploadManager" , "bytesCurrent" + bytesCurrent + " bytesTotal " + bytesTotal);
@Override
public void onError (int id, Exception ex) {
uploadMonitor.onFail("exception " + ex.toString());
uploadId = -1 ;
6.获取上传后的临时下载地址
具体公开的下载地址 还需要运维进行映射后提供
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(
bucketName, uploadKey)
URL url = uploadClient.generatePresignedUrl(urlRequest)
return url.toString()
7.上传gradle的配置
api 'com.amazonaws:aws-android-sdk-core:2.6.19'
api 'com.amazonaws:aws-android-sdk-s3:2.6.19'
api 'com.amazonaws:aws-android-sdk-ddb:2.6.19'
yeyan1996
JavaScript
1982
来碗盐焗星球
JavaScript
掘金·金石计划
5.2w
ssh_晨曦时梦见兮
JavaScript
24.7w
JessYan
GitHub
Android