引入依赖(依赖冲突可使用maven helper插件来排除,或者通过启动异常进行判断,或者看官方文档寻找答案)
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.5.0</version>
<exclusions>
<exclusion>
<artifactId>aliyun-java-sdk-core</artifactId>
<groupId>com.aliyun</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.cloud/aliyun-oss-spring-boot-starter -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>aliyun-oss-spring-boot-starter</artifactId>
<version>1.0.0</version>
<exclusions>
<exclusion>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</exclusion>
</exclusions>
</dependency>
key相关的配置
alibaba:
cloud:
access-key: *********
secret-key: *********
oss:
endpoint: oss-cn-beijing.aliyuncs.com
bucket: gulimall-huo
controller相关代码(这里为通过后端获取签名后直传方式)
@RestController
public class OSSController {
@Resource
private OSS ossClient;
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
@Value("${alibaba.cloud.access-key}")
String accessId;
@Value("${alibaba.cloud.oss.endpoint}")
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint;
@Value("${alibaba.cloud.secret-key}")
String accessKey;
@Value("${alibaba.cloud.oss.bucket}")
// 填写Bucket名称,例如examplebucket。
String bucket;
@RequestMapping(value = "/oss/policy")
public R policy(){
// 填写Host地址,格式为https://bucketname.endpoint。
String host = "https://" + bucket + "." + endpoint;
// 用每一天的时间日期当文件夹
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
String dir = format+"/";
Map<String, String> respMap = null;
// 创建ossClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
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 = new LinkedHashMap<>();
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));
// respMap.put("expire", formatISO8601Date(expiration));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return R.ok().put("data",respMap);
}
}
标签:存储,endpoint,String,oss,respMap,aliyun,put
From: https://www.cnblogs.com/huoziqi/p/17558769.html