demand
The project is a video platform where users create works and upload them to the server, just like Tiktok on SITE B. Due to the small bandwidth of the master server, the architecture design is that the client (Android/iOS) uploads files to ali Cloud OSS, and then uploads the file URL to the background through the interface to realize the upload operation.
Ali Cloud console operation
This assumes that you have already carried out the pre-operation, namely: create ali cloud account -> open OSS service -> create Bucket, if you have not done these operations can go to Baidu Google, not described here.
Create ali Cloud RAM account
Since Ali Cloud does not allow clients to directly log in to OSS using supermanaged accounts, we need to give clients a temporary identity for uploading files. STS temporary authorization to access OSS ←
Temporary access authorization
Build mobile application direct transmission service quickly← Open the STS service according to the instructions in this document
Go to the following steps,Just do 1 and 2That’s it. The second step is done by the background, it is best to let your background write an interface, every time you request this interface, he will use SDK to go to Ali Cloud to apply for a group of data. thisconfig.json
The first three parameters are the values you obtained when you created them in Step 1. The fourth parameter leaves him alone. The fifth parameter points to a file. New is there. Now let’s go to the console.
RAM console grants permissions
Ali Cloud RAM Access Control ← Log in to this console
① On the left side, find “RAM Role Management”. There is a role that was created automatically in step 1. Click “Add Permissions”.
② An operation panel will pop up on the right. Enter “OSS” in the input box and click the result to add it to the selected one. And then finally click on the confirm below
Click “Rights Management” -> “Add Rights”, search for “OSS” as before, and add all roles
④ Then we find this item in the added permission list, click the blue word to enter
⑤ Copy the text of the policy content
The copied content should look like this:
{
"Statement": [{"Action": "oss:*"."Effect": "Allow"."Resource": "*"}]."Version": "1"
}
Copy the code
Remember the config.json? The fifth argument points to a file, and the JSON is the content of that file. You can save it as policy. TXT and change it to config.json like this:
{
"AccessKeyID" : "Your AccessKeyID"."AccessKeySecret" : "Your AccessKeySecret"."RoleArn" : "Your RoleArn"."TokenExpireTime" : "900"."PolicyFile": "Policy.txt"
}
Copy the code
OSS Console Authorization
(1) the loginAli Cloud OSS console
② Find the bucket you created, click it, and then click the one on the leftFile management
And then order againauthorization
③ The operation panel will pop up on the right. ClickThe new authorization
4 Select an authorized userThe child account
, and then select the RAM user that the system created for you in Step 1, because we need to upload files here, soPermission to operate
chooseRead/write
And finally remember to click ok.
Android code manipulation
Now that the damn console is finally out of the way, let’s go inside Android Studio.
The SDK guide package
Repeat after me: Gradle method good!
implementation 'com.aliyun.dpa:oss-android-sdk:+'
Copy the code
Obtain temporary authentication data
There are two authentication modes: STS and RAM. Here, RAM is used as an example to request the interface written in the background in Step 2. You get data like this:
{
"StatusCode":200."AccessKeyId":"STS.NTao********"."AccessKeySecret":"* * * * * * * * * * * * * *"."Expiration":"2020-12-28T07:58:34Z"."SecurityToken":"This thing is very, very long and usually ends with equals equals."
}
Copy the code
StatusCode == 200 (AccessKeyId, AccessKeySecret, SecurityToken) If the request fails, data like this is returned:
{
"StatusCode":500."ErrorCode":"Error code"."ErrorMessage":"Error message"
}
Copy the code
If an error is reported, the StatusCode == 500 will be returned. I recommend that any error not 200 be treated as an error, and then report the error code and error message to the background.
Upload files to OSS
Kotlin code snippet, this is written as a reference to the official documentation, and for those of you who still use Java you can refer to the official documentation, just remember what parameters to put in each place. Alicloud official Android SDK documentation – initialize alicloud official Android SDK documentation – simple upload
val credentialProvider = OSSStsTokenCredentialProvider(AccessKeyId, AccessKeySecret, SecurityToken)// These three are obtained by the interface just now
//// If using stsAuth authentication mode, use the following constructor, if using RAM authentication mode, use the above constructor
// stsServer = "STS application server address, for example http://abc.com"
// val credentialProvider = OSSAuthCredentialsProvider(stsServer);
//// Configuration class If this parameter is not specified, the default configuration is displayed.
// ClientConfiguration conf = new ClientConfiguration();
// conf.setConnectionTimeout(15 * 1000); // The connection timed out, 15 seconds by default.
// conf.setSocketTimeout(15 * 1000); // The socket timed out, 15 seconds by default.
// conf.setMaxConcurrentRequest(5); // Maximum number of concurrent requests, 5 by default.
// conf.setMaxErrorRetry(2); // Maximum number of retries after a failure. The default value is 2.
// Endpoint is the OSS address configured in the background
val oss = OSSClient(applicationContext, endpoint, credentialProvider)
// Construct the upload request
//bucketName Specifies the name of the bucket
// The path where the objectKey file is stored on the OSS and its file name. For example, I want to save it in the bucket image directory. The file name is 1.jpg. So I'm going to say "image/1.jpg"
// Note: If objectKey contains a subdirectory, manually create the subdirectory on the OSS console in advance, or have the background create the subdirectory with administrator privileges. Temporary users of the client do not have permission to create the subdirectory.
//localPath Specifies the local file path
put = PutObjectRequest(bucketName, objectKey, localPath)
// The progress callback can be set for asynchronous uploading. You can do progress bars and things like that here, but notice that this is an IO thread, so make sure you add runOnUiThread
put.progressCallback = OSSProgressCallback { request, currentSize, totalSize ->
Log.d("PutObject"."currentSize: $currentSize totalSize: $totalSize")}val task: OSSAsyncTask<*> = oss.asyncPutObject(put, object: OSSCompletedCallback<PutObjectRequest? , PutObjectResult> {override fun onSuccess(request: PutObjectRequest? , result:PutObjectResult) {
Log.d("PutObject"."UploadSuccess")
Log.d("ETag", result.eTag)
Log.d("RequestId", result.requestId)
// The upload is complete
// Successfully uploaded URLS are not returned here. You can go to the console to check. The domain name in front is the domain name configured by OSS, and you can directly join objectKey in the back. It is a common address that can be accessed and downloaded directly
}
override fun onFailure(request: PutObjectRequest? , clientExcepion:ClientException? , serviceException:ServiceException?). {
// This is an errorclientExcepion? .printStackTrace()if(serviceException ! =null) {
// The service is abnormal.
Log.e("ErrorCode", serviceException.errorCode)
Log.e("RequestId", serviceException.requestId)
Log.e("HostId", serviceException.hostId)
Log.e("RawMessage", serviceException.rawMessage)
}
}
})
// task.cancel(); // You can cancel the task.
// task.waitUntilFinished(); // Wait for the task to complete.
Copy the code