“This is my 13th day of the Novembermore Challenge.The final text challenge in 2021”.
preface
I believe we all know, integration ali Cloud OSS object storage stepped on a little pit. The correct integration steps are recorded here for quick integration later. If you are interested in official documents, you can read them by yourself.
The attachment upload
The common upload logic is that the Web side uploads files to the application server, and the application server uploads files to the OSS. The specific process is shown in the figure below.
However, this scheme has the following disadvantages:
- Slow speed, after two transmission, the time at least doubled
- Wasted performance in case the user base gets too big and the server becomes our bottleneck
Best solution client signature direct transmission
Because the upstream traffic of OSS is free, data directly transmitted to OSS can greatly reduce the speed, save server resources, and relieve server pressure.
- The user requests the application server to upload the Policy.
- The application server uploads the Policy and signature to the user.
- Users directly send file upload requests to the OSS.
Integration steps
1. Enable the Ali Cloud OSS object storage service
This is not introduced, login Ali cloud platform, follow the guide operation on the line
2. Obtain the following parameters
- endpoint
- accessKeyId
- accessKeySecret
- bucketName
endpoint
Click the Bucket list -> Create Bucket -> Fill in the Bucket name -> Select region -> Different endpoints will be given according to the region
So here we havebucketName,endpoint
If you forget, you can look it up in the following path
AccessKeyId and accessKeySecret
Click your profile picture in the upper right corner –> AccessKey Management
You can create a user that has only OSS related rights by creating a subaccount
Create a user
Create accessKey, make sure to record the generated, the page closed can only be re-generated
Add permission to a user
Adding read and write Permissions
This is where all the prep work is done, and then code integration
SpringBoot code integration
1. Introduce dependencies
<! -- Ali Cloud OSS Storage -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.13.2</version>
</dependency>
Copy the code
2. The configuration file defines attribute values
Add configuration properties to application.yml
# Ali Cloud OSS
aliyun:
oss:
endpoint: oss-cn-shanghai.aliyuncs.com
accessKeyId: LTAI5tHZ1reFzUUuZmCr88dn
accessKeySecret: ayKgKy4BY1sk3xO4JfnakB70gLaUI9
bucketName: thinkfon-member
Copy the code
3. Add configuration objects
Automatically configure OSSClient objects
@Component
public class OssClient {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Bean
public OSS getOSSClient(a) {
return newOSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); }}Copy the code
4. Write and acquirepolicyinterface
@RestController
@RequestMapping("/oss")
public class OSSController {
@Autowired
OSS ossClient;
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@apiOperation (" Get signature policy")
@GetMapping("/policy")
public Map<String, String> policy(a) {
// The host format is bucketname.endpoint
String host = "https://" + bucketName + "." + endpoint;
// callbackUrl is the URL of the callback server. Please configure the following IP and Port as your own real information.
// String callbackUrl = "http://88.88.88.88:8888";
String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// Store in folders by date
String dir = today + "/"; // The prefix specified when the user uploads the file.
Map<String, String> respMap = null;
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
The maximum file size supported by PostObject request is 5 GB, that is, CONTENT_LENGTH_RANGE is 5*1024*1024*1024.
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0.1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
respMap = new LinkedHashMap<String, String>();
respMap.put("accessid", accessKeyId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
} finally {
ossClient.shutdown();
}
returnrespMap; }}Copy the code
We’re done here on the server side
5. Test
The call to the Get Policy interface returns
{
"accessid": "LTAI5tHZ1ro3zUUuZmCr88dn"."policy": "eyJleHBpcmF0aW9uIj1iMjAyMS0xMS0xNVQwOTozODowOS4zOThaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjA wMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCIyMDIxLTExLTE1LyJdXX0="."signature": "3K/6hXZPCYCNBwUFBaec7CmAa70="."dir": "The 2021-11-15 /"."host": "https://thinkfon-member.oss-cn-shanghai.aliyuncs.com"."expire": "1636969089"
}
Copy the code
field | describe |
---|---|
accessid | AccessKey ID requested by the user. |
host | Domain name used by the user to send an upload request. |
policy | The user form upload Policy. The Policy is a Base64 encoded string. For details, seePost Policy. |
signature | String after the Policy is signed. For details, seePost Signature. |
expire | The Policy expiration time specified by the server, in the format of Unix timestamp (number of seconds since January 01, 1970 UTC time). |
dir | Limit the prefixes of uploaded files. |