Simple Storage Service(S3)
这个功能简单地可以理解成百度云盘,且提供了给文件打上关于Key,Value这样便于查找的功能,比如APP的用户数据(录音、小视频等等)就可以通过这个功能进行储存。
还有比较方便的一点是它可以通过各种方式进行访问,包括在网页上直接拖拽、Python、Android等方式都是可以的。本文就记录一下自己在Android平台上设置S3并上传文件的过程。
账号注册
需要选择国际版AWS(支持Amplify自动搭建操作),国内的版本虽然有S3但是搭建方式比较复杂。每个账户是可以免费试用一年的,需要有支持美元付款的信用卡。
开始
参考官方教程
https://aws-amplify.github.io/docs/android/start?ref=amplify-android-btn
首先安装Amplify,它可以理解成自动搭建的脚本(类似于Gradle?),通过简单的几个设置就能搭出所需要的功能。(下面的内容上述网址均有)
首先安装 Node.js®,然后打开cmd安装Amplify
$ npm install -g @aws-amplify/cli
$ amplify configure
这里的amplify configure
主要涉及到账号登陆,并新建了一个Android工程专用的IAM账号,默认是具有Administrator权限的,后续如果APP需要发布的话,需要手动在IAM控制台中将其权限调整为所需的范围。
然后我们开始安卓工程相关的设置。
Android工程设置
跟着官方文档https://aws-amplify.github.io/docs/android/start?ref=amplify-android-btn一直做到Step 3
后面的Step 4的API是一个Demo功能,只用S3的话是不需要的。
关于
project/build.gradle
app/build.gradle
等等gradle
文件是怎么样的我最后会贴一个(后面还要加上S3的,这里暂时先不贴)。amplify init
的过程如图:这个过程会在IAM账号(可以理解成大号的马甲,在https://console.aws.amazon.com/iam/home#/roles中查看)中增加两个和这个Project相关的账号。
Storage 设定/ Step 1 添加验证
先阅读官方文档 https://aws-amplify.github.io/docs/android/storage
首先要添加验证,参考https://aws-amplify.github.io/docs/android/authentication
这里简单起见,我们就直接使用匿名身份上传了。关于Authentication这一部分的内容在后续的博客会有提到。
amplify add auth
这里再
amplify push
一下,设置好本地和云端,就会发现Android工程里面的awsconfiguration.json
变掉了,添加了和账户验证相关的一些信息,另外IAM页面里面又多了两个账号。Storage 设定/ Step 2 添加Storage功能
amplify add storage
注意Guest用户也要选
read/write
amplify push
就会发现awsconfiguration.json
里面多了和S3储存桶相关的一些信息,同时会自动新建一个S3储存桶。(可在https://s3.console.aws.amazon.com/s3/home查看)
Storage 设定/ Step 3 Android程序编写
新建测试界面
app:build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.administrator.anothers3uploadtest"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
//Base SDK
implementation 'com.amazonaws:aws-android-sdk-core:2.12.+'
//For AWSMobileClient only:
implementation 'com.amazonaws:aws-android-sdk-mobile-client:2.12.+'
//Storage
implementation 'com.amazonaws:aws-android-sdk-s3:2.12.+'
implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.12.+@aar') { transitive = true }
implementation ('com.amazonaws:aws-android-sdk-auth-userpools:2.12.+@aar') { transitive = true }
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
project:build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
//appsync
classpath 'com.amazonaws:aws-android-sdk-appsync-gradle-plugin:2.7.+'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
MainActivity.java
package com.example.administrator.anothers3uploadtest;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.mobile.client.Callback;
import com.amazonaws.mobile.client.UserStateDetails;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferService;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility;
import com.amazonaws.services.s3.AmazonS3Client;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails userStateDetails) {
switch (userStateDetails.getUserState()){
case SIGNED_IN:
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView) findViewById(R.id.text);
textView.setText("Logged IN");
}
});
break;
case SIGNED_OUT:
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView) findViewById(R.id.text);
textView.setText("Logged OUT");
}
});
break;
default:
AWSMobileClient.getInstance().signOut();
break;
}
}
@Override
public void onError(Exception e) {
Log.e("INIT", e.toString());
}
});
getApplicationContext().startService(new Intent(getApplicationContext(), TransferService.class));
((Button)findViewById(R.id.save_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveToFile(String.valueOf(((TextView)findViewById(R.id.inputText)).getText()));
}
});
((Button)findViewById(R.id.upLoadButton)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadWithTransferUtility();
}
});
}
public void saveToFile(String inputText){
FileOutputStream out=null;
BufferedWriter writer = null;
try{
out = openFileOutput("data.txt", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
}catch (IOException e){
e.printStackTrace();
}finally {
{
try{
if(writer!=null)
writer.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
public void uploadWithTransferUtility() {
TransferUtility transferUtility =
TransferUtility.builder()
.context(getApplicationContext())
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.s3Client(new AmazonS3Client(AWSMobileClient.getInstance()))
.build();
TransferObserver uploadObserver =
transferUtility.upload(
"data.txt",
new File(getFilesDir()+"/data.txt"));
// Attach a listener to the observer to get state update and progress notifications
uploadObserver.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
if (TransferState.COMPLETED == state) {
// Handle a completed upload.
}
}
@Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100;
int percentDone = (int)percentDonef;
Log.d("YourActivity", "ID:" + id + " bytesCurrent: " + bytesCurrent
+ " bytesTotal: " + bytesTotal + " " + percentDone + "%");
}
@Override
public void onError(int id, final Exception ex) {
// Handle errors
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView) findViewById(R.id.text);
textView.setText("Error"+ex);
}
});
}
});
// If you prefer to poll for the data, instead of attaching a
// listener, check for the state and progress in the observer.
if (TransferState.COMPLETED == uploadObserver.getState()) {
// Handle a completed upload.
}
Log.d("YourActivity", "Bytes Transferred: " + uploadObserver.getBytesTransferred());
Log.d("YourActivity", "Bytes Total: " + uploadObserver.getBytesTotal());
}
}
这里会报错权限问题,我找了很久问题在哪…
com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: *********************), S3 Extended Request ID: ********************************************************************************************************************
这里我参考了https://github.com/awslabs/aws-sdk-android-samples/tree/master/S3TransferUtilitySample
发现是可以手动配置的,我就是在手动配置之后偶然发现居然成功了?
最后发现原来是自动配置的Unauthorized Role的权限仍然不足,需要手动加上S3完全的权限。
对比一下权限(上面的是手动添加的,下面的是自动生成的):
不过并不知道自动生成的为什么有写入权限还是写不进去……
后续
发现是自己文档读的不到位,漏掉了下面这一个关键的地方:
需要注意IAM账号和上图中的
users
是不一样的,我们需要手动打开储存同的Public权限,如下图:然后上传的Key也要设置成对应的
public
Storage 设定/ Step 4 成果预览
手机上按下保存字符串
然后上传,最后就能在其对应的储存桶里面看到对应的data.txt
了。
TODO
这个Project本意是用来采集一些样本用来做机器学习训练集的,因此只需要匿名上传功能,因此只关注到了未授权的匿名操作,想要拓展的话后续会看一下使用账号的上传方式。