1.目的
微信选择图片后成功上传图片至华为云中,并能在小程序中成功预览
2.操作步骤
1.对目标桶进行跨域设置
详情见:https://support.huaweicloud.com/usermanual-obs/zh-cn_topic_0066036542.html
2.微信小程序域名白名单设置
1.获取目标桶的访问域名,复制;
2.小程序-开发管理-开发设置-服务器域名
点击修改,粘贴至request合法域名,uploadFile合法域名,downloadFile合法域名;
3.新增对应的代码(直接见附录有完成版)
1.post新增policy字段签名,配置js-base64,可通过npm下载
const Base64 = require('./Base64.js');
function getPolicyEncode(policy) {
const encodedPolicy = Base64.encode(JSON.stringify(policy));
return encodedPolicy;
}
const OBSPolicy = {
//设定policy内容
expiration: '20xx-xx-xxT12:00:00.000Z',
conditions: [
{ bucket: config.bucket }, //Bucket name
{ key: fileName },
{ 'content-type': 'image/png' },
{ 'x-obs-acl': 'public-read' }
]
}
const policyEncoded = getPolicyEncode(OBSPolicy) //计算policy编码值
2.配置计算签名signature,配置crypto,可通过npm下载
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');
const Base64 = require('./Base64.js');
//利用SK计算Signature信息
function getSignature(policyEncoded, SecretKey){
const bytes = Crypto.HMAC(Crypto.SHA1, policyEncoded, SecretKey, {
asBytes: true
});
const signature = Crypto.util.bytesToBase64(bytes);
return signature;
}
const signature = getSignature(policyEncoded, config.SecretKey)
3.配置对应的config,包含AccessKeyId,SecretKey,bucket,EndPoint
var Configuration = {
AccessKeyId: 'AccessKeyId' , //AK
SecretKey: 'SecretKey', //SK
bucket: 'bucketName' //目标桶名,
EndPoint: `https://${bucketName}.obs.xxxx.myhuaweicloud.com` //完整的桶访问域名
}
4.结合微信小程序uploadFile上传至华为云
const fileName = dayjs(new Date().getTime()).format('YYYYMMDDHHmmss') + '.jpg' //文件名称
//微信小程序的上传方法
wx.uploadFile({
url: config.EndPoint, //上传路径
filePath: filePath, //图片的临时路径
name: 'file',
header: {
'content-type': 'multipart/form-data; boundary=-9431149156168'
},
formData: {
AccessKeyID: config.AccessKeyId, //ak
policy: policyEncoded, //policy字段签名
signature: signature, //signature字段
key: fileName, //文件名
'content-type': 'image/png',
'x-obs-acl': 'public-read'
},
success: function (res) {
console.log(res.statusCode) //打印响应状态码
if (res.statusCode == '204') {
console.log('上传图片成功', res)
that.triggerEvent('getImgList', [config.EndPoint + '/' + fileName]) //在华为云上的访问地址,预览图片可用其展示
} else {
console.log('上传图片失败', res)
}
},
fail: function (e) {
console.log(e)
}
})
3.选择图片后的操作
wx.chooseImage({
count: 1, //保证总上传个数不会超出限制
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: function (res) {
var imgs = res?.tempFilePaths || []
OBSuploadFile(imgs[0], that)
}
})
},