基本的なファイルのアップロードとダウンロードのプロセスを以下に示します。詳細については、このプロジェクトの以下のディレクトリを参照してください。
サンプルディレクトリ (ローカルファイルアップロード、ファイルダウンロード、再開可能なアップロード、コールバック設定のデモを含む) 詳細
git clone project を実行して、必要なパラメータを設定することもできます。
次に、次のようにプロジェクトを実行します。
ステップ 1. OSSClient の初期化
初期化プロセスには、主に、エンドポイント設定、認証モード設定、およびクライアントパラメータ設定の各ステップが含まれます。自己署名モードと STS 認証モードの 2 つの認証モードが利用できます。STS 認証を使用するには、RAM の詳細についてResource Access Management
を参照してください。RAM サービスを有効にし、RAM サービスを学習し、サブアカウント AccessKeyId、SecretKeyId、および RoleArn を取得する方法を学習したと仮定します。
スクリプトファイルの AccessKeyId、SecretKeyId、および RoleArn のパラメータ情報を入力します。Python でローカルの HTTP サービスを有効にすることができます。クライアントコードを使用してローカルサービスにアクセスし、StsToken.AccessKeyId、StsToken.SecretKeyId、および StsToken.SecurityToken を取得します。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// We recommend that you initialize OSSClient using STS on the mobile device.
// For more information, see STS instructions in the sample.(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.SecurityToken>");
//If the configuration class is not set, use the default configurations. For more information, see the configuration class.
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // Connection time-out. The default value is 15 seconds.
conf.setSocketTimeout(15 * 1000); // Socket time-out. The default value is 15 seconds.
conf.setMaxConcurrentRequest(5); // The maximum number of concurrent requests. The default value is 5.
conf.setMaxErrorRetry(2); // The maximum number of retry attempts after each failed attempt. The default value is 2.
//When the feature is enabled, you can view logs in the console and write a log file into the mobile phone SD card under SDCard_path\OSSLog\logs.csv. This feature is disabled by default.
//The logs record the request data, returned data, and exception information in OSS operations.
//Such as requestId and response header
//Android_version: 5.1 Android version
//mobile_model: XT1085 Android mobile phone model
//Network_state: connected Network status
//network_type: WIFI Network connection type
//Specific operations:
//[2017-09-05 16:54:52] - Encounter local execpiton: //java.lang.IllegalArgumentException: The bucket name is invalid.
//A bucket name must:
//1) be comprised of lower-case characters, numbers, or dash(-);
//2) start with lower case or numbers;
//3) be between 3-63 characters long.
//------>end of log
OSSLog.enableLog();
OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
OSSClient を使用したアップロードおよびダウンロードリクエストの初期化はスレッドセーフです。複数のタスクを同時に実行できます。
ステップ 2. ファイルのアップロード
すでにバケットを OSS コンソールに持っていると仮定します。次のコードを使用して、ローカルファイルを OSS にアップロードできます。
// Construct an upload request
PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectKey>", "<uploadFilePath>");
// You can set progress callback during the asynchronous upload
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
}
});
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("PutObject", "UploadSuccess");
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// Request exception
if (clientExcepion != null) {
// Local exception, such as a network exception
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Service exception
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
// task.cancel(); // You can cancel the task
// task.waitUntilFinished(); // Wait until the task is complete
ステップ 3. 指定したファイルのダウンロード
次のコードは、指定されたobject
をダウンロードします(返されるデータの入力ストリームを処理する必要があります)。
// Construct a file download request.
GetObjectRequest get = new GetObjectRequest("<bucketName>", "<objectKey>");
OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
@Override
public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// Request succeeds
Log.d("Content-Length", "" + getResult.getContentLength());
InputStream inputStream = result.getObjectContent();
byte[] buffer = new byte[2048];
int len;
try {
while ((len = inputStream.read(buffer)) != -1) {
// Process the downloaded data.
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// Request exception
if (clientExcepion != null) {
// Local exception, such as a network exception
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Service exception
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
// task.cancel(); // You can cancel the task
// task.waitUntilFinished(); // If necessary, wait until the task is complete