1. 开通阿里云对象存储
- 先进入阿里云对象存储控制台
- 创建一个Buket
- AccessKey 开通 (使用子用户的AccessKey)
创建用户
添加权限
获取到 AccessKey ID 和 AccessKey Secret
2. 上传服务
获取pom依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>
yml 配置
服务端上传
代码示例一: (后台上传)
@SpringBootTest
class FyjmallThirdPartyApplicationTests {
@Autowired
private OSS oss;
@Test
void contextLoads() throws FileNotFoundException {
// 上传内容到指定的存储空间(bucketName)并保存为指定的文件名称(objectName)。
String content = "Hello OSS";
InputStream inputStream = new FileInputStream("E:\\0d40c24b264aa511.jpg");
oss.putObject("fyjmall", "0d40c24b264aa511.jpg", inputStream);
// 关闭OSSClient。
oss.shutdown();
System.out.println("上传完成");
}
}
服务端生成签名,给前台直接上传
代码示例:
yml配置
@RestController
public class OssController {
@Autowired
OSS ossClient;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endpoint;
@Value("${spring.cloud.alicloud.oss.bucket}")
private String bucket;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@RequestMapping("/oss/policy")
public R policy() {
String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
// callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
// String callbackUrl = "http://88.88.88.88:8888";
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));
// respMap.put("expire", formatISO8601Date(expiration));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return R.ok().put("data",respMap);
}
}
允许跨域设置