After enabling "server-side signature and direct transfer" of Alibaba Cloud Object Storage OSS, the file upload function was tested and the server-side signature data was successfully obtained. The details are as follows:
{
"msg":"success","code":0,"data":{
"accessid":"L***t","policy":"ey***XX0=","signature":"EqsbPoxA/V***I=","dir":"2021-01-07/","host":"https://***.oss-cn-beijing.aliyuncs.com","expire":"1609993896"}}
However, subsequent file uploads were not performed.
Cause of the problem: The details of the policy() method of beforeUpload(file) in src\components\upload\singleUpload.vue are as follows:
beforeUpload(file) {
let _self = this
return new Promise((resolve, reject) => {
policy()
.then(response => {
console.log('返回的数据:', response)
_self.dataObj.policy = response.data.policy
_self.dataObj.signature = response.data.signature
_self.dataObj.ossaccessKeyId = response.data.accessid
_self.dataObj.key = response.data.dir + getUUID() + '_${filename}'
_self.dataObj.dir = response.data.dir
_self.dataObj.host = response.data.host
resolve(true)
})
.catch(err => {
reject(false)
})
})
}
The policy() method requires a data object to obtain data. The details of OssController are as follows:
public Map<String, String> policy() {
......
Map<String, String> respMap = null;
......
return respMap ;
}
The return value is a Map type, which is obviously not required by the policy() method.
Solution: Modify OssController as follows:
public R policy() {
......
Map<String, String> respMap = null;
......
return R.ok().put("data",respMap);
}
After the modification, I tested again and a new error occurred:
Access to XMLHttpRequest at 'http://***.oss-cn-beijing.aliyuncs.com/' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. upload.js?c0e8:599 POST http://***.oss-cn-beijing.aliyuncs.com/ net::ERR_FAILED
Cause of new problem:
The browser directly submits the file and the following dataObj to the object storage in post mode, resulting in a cross-domain request without cross-domain settings. , the request was intercepted.
data() {
return {
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: ''
// callback:'',
},
dialogVisible: false
}
}
New problem solution:
Refer to Alibaba Cloud official documentation "Direct transmission after server signature" 《Java》, 《Python》, in "Code Example" "PHP" or "GO"'s "Step 3: Modify CORS ”, the details are excerpted as follows:
客户端进行表单直传到OSS时,会从浏览器向OSS发送带有Origin的请求消息。OSS对带有Origin头的请求消息会进行跨域规则(CORS)的验证。因此需要为Bucket设置跨域规则以支持Post方法。
1、登录OSS管理控制台。
2、单击Bucket列表,之后单击目标Bucket名称。
3、单击权限管理 > 跨域设置,在跨域设置区域单击设置。
4、单击创建规则,配置如下:
来源:* (* 代表所有请求);
允许Methods:POST;
允许Headers:*
(其它选项默认即可。)
After the setting is completed, the test upload is successful.
At this point, the main issues related to direct transmission after server signature have been solved.