后台获取签名
public Map<String, String> getPolicy(String dir) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Map<String, String> respMap = new LinkedHashMap<String, String>();
try {
Date expiration = new Date(expireEndTime);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
respMap.put("accessid", accessKeyId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("fileName", UUID.randomUUID().toString());
respMap.put("host", bucketUrl);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
respMap.put("callback", "");
ossClient.shutdown();
return respMap;
} catch (UnsupportedEncodingException ex) {
respMap.put("msg", ex.getMessage());
return respMap;
}
}
小程序端上传图片
changeLogo () {
let that = this
let uploadData = {
dir: "logo"
}
// 获取密钥
http.httpPost('/api/aliyun/index', uploadData).then((res) => {
if (res.dir != undefined) {
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: (sres) => {
let tempFilePaths = sres.tempFilePaths
if (tempFilePaths.length > 0) {
// 返回的tempFilePaths是一个数组,获取第一个
let currentPath = tempFilePaths[0]
let fileRandName = Date.now() + "" + parseInt(Math.random() * 1000)
// "http://tmp/wxdc9fb31b489a357b.o6zAJs6pXFprbwemLvExiLPvggNI.zsYxnrUtezDcf465e333c5431588d5adc03a5dec1d91.jpeg"
// 获取后缀
let pathArr = currentPath.split('.')
let ext = pathArr[3]
let fileKey = uploadData.dir + '/' + fileRandName + '.' + ext
wx.uploadFile({
url: res.host,
filePath: currentPath,
name: 'file',
formData: {
name: currentPath,
key: fileKey,
policy: res.policy,
OSSAccessKeyId: res.accessid,
signature: res.signature,
success_action_status: "200"
},
success: (ures) => {
if (ures.statusCode == 200) {
let car = {
id: that.data.id,
image: res.host + '/' + fileKey,
cbid: that.data.cbid,
licence: that.data.licence,
isDefault: that.data.isdefault,
sort: that.data.sort
}
that.setData({
car: car
})
}
}
})
}
}
})
}
}).catch((error) => {
wx.showToast({
title: error,
})
})
}