- 阿里云服务器上开通OSS服务,很简单
- 专业数据简介
Bucket 存储空间,基本上一个项目创建一个bucket
Object 存储的对象
Region 区域,存储区域
EndPoint 访问域名
访问秘钥 上传文件需要使用秘钥 - 创建一个bucket然后上传上去之后,就可以在公网上访问了。
- 服务端签名,前端上传图片策略
- 在阿里云上的控制台配置子账户,获取accesskey,和id
- 给这个子账号添加OSS权限
- springcloudalibaba 整合的oss 有問題,直接用原生的
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
- 创建一个新的模块来整合所有第三方服务,代码直接照抄官方demo即可,前端上传文件之前先找服务端获取信息,然后拿着这些信息把图片上传到OSS,
@RestController
@RequestMapping("third/oss")
public class OssController {
@Value("${oss.accessId}")
private String accessId;
@Value("${oss.accessKey}")
private String accessKey;
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.bucket}")
private String bucket;
@GetMapping("/policy")
public R<Map<String, String>> test() {
String host = "https://" + bucket + "." + endpoint;
String dir = "user-dir-prefix/";
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(StandardCharsets.UTF_8);
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
Map<String, String> 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));
JSONObject jasonCallback = new JSONObject();
jasonCallback.put("callbackBody",
"filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
respMap.put("callback", base64CallbackBody);
return R.ok(respMap);
} catch (Exception ignore) {
}
return null;
}
}