心有千斤坠,却无一字言
使用对象存储,将文件上传到阿里云分布式文件服务器上。
帮助文档:
整合spring-cloud:
spring简单上传:
上传策略:服务端签名后直传
使用示例:
登录阿里云账号
创建一个bucket
创建子用户,获取Endpoint
、AccessKey ID
、AccessKey Secret
分配权限
在nacos
注册中心填写相应的信息
spring:
cloud:
alicloud:
oss:
endpoint:
bucket:
access-key:
secret-key:
在项目中配置bootstrap.yml
spring:
application:
name: gulimall-third-party
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
namespace:
extension-configs[0]:
data-id: oss.yaml
group: DEFAULT_GROUP
refresh: true
建立添加文件上传获取签名的Controller
@RestController
public class OssController {
@Autowired
OSS ossClient;
@Value("${spring.cloud.alicloud.oss.endpoint}")
String endpoint;
@Value("${spring.cloud.alicloud.oss.bucket}")
String bucket;
@Value("${spring.cloud.alicloud.access-key}")
String accessId;
@Value("${spring.cloud.alicloud.secret-key}")
String accessKey;
@RequestMapping("/oss/policy")
public Map<String, String> policy(){
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=null;
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<String, String>();
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;
}
}
添加上传跨域规则
标签:文件,String,spring,OSS,respMap,put,上传,oss,cloud From: https://www.cnblogs.com/l12138h/p/16709184.html