此时你需要保存好AccessKeyID和AccessSecret,否则这个页面关闭后就找不到了。
maven依赖#
Copy
com.aliyun.oss
aliyun-sdk-oss
3.10.2
最新版本可以看这里:https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.807.39fb4c07GmTHoV
测试上传#
测试代码
Copy
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = “http://oss-cn-hangzhou.aliyuncs.com”;
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = “”;
String accessKeySecret = “”;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest("", “test”, new File(“C:\Users\82131\Desktop\logo.jpg”));
// 上传文件。
ossClient.putObject(putObjectRequest);
// 关闭OSSClient。
ossClient.shutdown();
image.png
测试成功后就可以看到test图片了,如图:
image.png
服务端签名实现流程# 修改CORS#
客户端进行表单直传到OSS时,会从浏览器向OSS发送带有Origin的请求消息。OSS对带有Origin头的请求消息会进行跨域规则(CORS)的验证。因此需要为Bucket设置跨域规则以支持Post方法。
进入bucket后,选择权限管理 -》跨域设置 -》创建规则
image.png
后端代码#
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;
}
}
更详细的详细请查看这里:https://help.aliyun.com/document_detail/91868.html?spm=a2c4g.11186623.2.15.a66e6e28WZXmSg#concept-ahk-rfz-2fb
前端代码#
以element-ui组件为例,上传前BeforeUpload先调用后端的policy接口获取签名信息,然后带着签名等信息和图片直接上传到aliyun的OSS。
上传组件singleUpload.vue,需要改动action的地址:bucket的外网域名(在bucket的概览里面可以看到),该文件是谷粒商城项目的一个上传组件,我只是copy过来修改了一点点。
Copy
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(‘上传成功…’)
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)
}
}
}
引用SingleUpload组件的页面的示例代码:
Copy