Use Alibaba Cloud OSS's server-side direct transfer function after signature

At this time, you need to save the AccessKeyID and AccessSecret, otherwise you will not find it after closing this page.

maven dependency#
Copy

com.aliyun.oss
aliyun-sdk-oss
3.10.2 The

latest version can be viewed here: https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.807.39fb4c07GmTHoV

Test upload#
test code

Copy
// Endpoint takes Hangzhou as an example. Please fill in other regions according to actual conditions.
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// The Alibaba Cloud main account AccessKey has access to all APIs, which is very risky. It is strongly recommended that you create and use a RAM account for API access or daily operation and maintenance. Please log in to https://ram.console.aliyun.com to create a RAM account.
String accessKeyId = "";
String accessKeySecret = "";

// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest("", “test”, new File(“C:\Users\82131\Desktop\logo.jpg”));

// upload files.
ossClient.putObject(putObjectRequest);

// Close OSSClient.
ossClient.shutdown();
image.png

After the test is successful, you can see the test picture, as shown in the figure:
image.png

Server-side signature implementation process# Modify CORS# When the
client transfers the form directly to OSS, it will send a request message with Origin from the browser to OSS. OSS will verify cross-domain rules (CORS) for request messages with Origin headers. Therefore, it is necessary to set cross-domain rules for Bucket to support the Post method.
After entering the bucket, select Permission Management-"Cross Domain Settings-"Create Rule
image.png

Backend code#
Copy
@RestController
public class OssController {

@RequestMapping("/oss/policy")
public Map<String, String> policy() {
    String accessId = "<yourAccessKeyId>"; // 请填写您的AccessKeyId。
    String accessKey = "<yourAccessKeyId>"; // 请填写您的AccessKeySecret。
    String endpoint = "oss-cn-shenzhen.aliyuncs.com"; // 请填写您的 endpoint。
    String bucket = "bucket-name"; // 请填写您的 bucketname 。
    String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint

    String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    String dir = format + "/"; // 用户上传文件时指定的前缀。

    Map<String, String> respMap = new LinkedHashMap<String, String>();
    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
    try {
        long expireTime = 30;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        // PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为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("utf-8");
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);

        respMap.put("accessid", accessId);
        respMap.put("policy", encodedPolicy);
        respMap.put("signature", postSignature);
        respMap.put("dir", dir);
        respMap.put("host", host);
        respMap.put("expire", String.valueOf(expireEndTime / 1000));

    } catch (Exception e) {
        // Assert.fail(e.getMessage());
        System.out.println(e.getMessage());
    } finally {
        ossClient.shutdown();
    }
    return respMap;
}

}For
more details, please check here: https://help.aliyun.com/document_detail/91868.html?spm=a2c4g.11186623.2.15.a66e6e28WZXmSg#concept-ahk-rfz-2fb

Front-end code#
Take the element-ui component as an example. Before uploading, BeforeUpload first calls the back-end policy interface to obtain the signature information, and then uploads it directly to Aliyun's OSS with the signature and other information and pictures.
To upload the component singleUpload.vue, you need to change the action address: the external domain of the bucket (you can see it in the bucket overview). This file is an upload component of the Grain Mall project. I just copied it and modified it a little bit.

Copy

Click upload
Only jpg/png files can be uploaded, and no more than 10MB

export default {
name: ‘SingleUpload’,
props: {
value: String
},
data() {
return {
dataObj: {
policy: ‘’,
signature: ‘’,
key: ‘’,
ossaccessKeyId: ‘’,
dir: ‘’,
host: ‘’
// callback:’’,
},
dialogVisible: false
}
},
computed: {
imageUrl() {
return this.value
},
imageName() {
if (this.value != null && this.value !== ‘’) {
return this.value.substr(this.value.lastIndexOf(’/’) + 1)
} else {
return null
}
},
fileList() {
return [{
name: this.imageName,
url: this.imageUrl
}]
},
showFileList: {
get: function() {
return this.value !== null && this.value !== ‘’ && this.value !== undefined
},
set: function(newValue) {
}
}
},
methods: {
emitInput(val) {
this.KaTeX parse error: Expected 'EOF', got '}' at position 24: …put', val) }̲, handleRem…{filename}’
_self.dataObj.dir = response.dir
_self.dataObj.host = response.host
resolve(true)
}).catch(err => {
reject(false)
})
})
},
handleUploadSuccess(res, file) { console.log('Upload successful...') this.showFileList = true this.fileList.pop() this.fileList.push({ name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name) }) this.emitInput(this.fileList[0].url) } } } The sample code of the page referencing the SingleUpload component:









Copy

Absorbing material: www.goodsmaterial.com

Guess you like

Origin blog.csdn.net/weixin_45032957/article/details/108616491