long expireEndTime = System.currentTimeMillis() + 21600* 1000 ;
Date expiration = new Date(expireEndTime);
// 上传空间
String uploadDir = DateTimeUtils.getDateTime("yyyyMMdd", expiration);
PolicyConditions policyCons = new PolicyConditions();
policyCons.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyCons.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, uploadDir);
// 生成post请求策略
String postPolicy = ossClient().generatePostPolicy(expiration, policyCons);
byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
// 生成签名用于直连上传
String postSignature = ossClient().calculatePostSignature(postPolicy);
// 构建
OssPolicy ossPolicy = new OssPolicy();
ossPolicy.setPolicy(encodedPolicy);
ossPolicy.setAccessKeyId(ossConfig().getAccessKeyId());
ossPolicy.setSignature(postSignature);
ossPolicy.setExpireEndTime((expireEndTime - 28800 * 1000)/ 1000);
ossPolicy.setDir(uploadDir);
// 前端上传域名
ossPolicy.setHost(ossConfig().getHost());
let imgSignature = {}
if (!oldExpireEndTime || oldExpireEndTime <= Math.round(new Date().getTime() / 1000)) {
const { data } = await that.$api.generatePolicy()
imgSignature = data.body
uni.setStorageSync("imgSignature", imgSignature)
} else {
imgSignature = uni.getStorageSync("imgSignature")
}
const { accessKeyId, policy, signature, dir, host, expireEndTime } = imgSignature
const key = `${dir}/user-${userId}-${new Date().getTime()}.png`
const queryInfo = {
key,
policy,
OSSAccessKeyId: accessKeyId,
signature,
expireEndTime,
}
uni.uploadFile({
url: host,
filePath,
name: "file",
formData: queryInfo,
success: (res) => {
if (res.statusCode === 204) resolve(host + "/" + key)
else reject()
},
fail: (err) => {
reject()
},
})
policy在oss中也是需要设置的,可以先检查一下。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。