一湿镀、前言:
前段時(shí)間項(xiàng)目需求需要接入亞馬遜的S3云服務(wù)存儲(chǔ)視頻、圖片資源删顶,但是發(fā)現(xiàn)網(wǎng)上關(guān)于Android 端Amazon S3的資料寫的都不是特別充足,于是專門寫一篇給需要接入此功能的作為參考只锭。
二、接入
1煌贴、導(dǎo)包
//亞馬遜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
//亞馬遜客戶端對(duì)象
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);
// 設(shè)置上傳的鍵(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 {
//協(xié)程
val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
/**
* 初始化亞馬遜
*/
fun uploadAmazonUtil(myKey:String,loaclPath:String,result: (Boolean,String)->Unit){
try {
scope.launch(Dispatchers.IO) {
//調(diào)用上傳
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));
// 設(shè)置文件的ACL為公共讀取
putObjectRequest.setCannedAcl(CannedAccessControlList.PublicReadWrite);
//上傳
s3Client.putObject(putObjectRequest);
// 設(shè)置 URL 的過期時(shí)間為 1 小時(shí)
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);
}
}
}
繼承以上笙各,就可以上傳文件或者圖片就會(huì)成功,返回成功的地址础芍。