先阿里云oss后台管理配置,这里只是前端的操作,先获取后端接口返回的数据:
AccessKeyId, AccessKeySecret,SecurityToken,bucket,regionId,object_path,domain
bucket: OSS存储空间名称
domain: 域名地址
object_path: 保存至oss的文件路径
微信小程序配置域名白名单
import crypto from 'crypto-js.js'
import { Base64 } from 'base64.min.js'
//1.计算签名
function computeSignature(accessKeySecret, canonicalString) {
return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}
//2.设置policy过期时间
const date = new Date();
date.setHours(date.getHours() + 1);
const policyText = {
expiration: date.toISOString(), // 设置policy过期时间。
conditions: [
// 限制上传大小。
["content-length-range", 0, 1024 * 1024 * 1024],
],
};
const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string
const signature = computeSignature(AccessKeySecret, policy) //签名
const host = `https://${bucket}.${regionId}.aliyuncs.com` //存储空间的访问域名,例如https://xxxx.xxxx.aliyuncs.com
//3.选择图片并上传
wx.chooseImage({
count: 1,
sizeType:['compressed'],
extension:['jpg','png'],
success:(file)=>{
//如果是多图,循环执行
//设置图片名,保存地址
let fileName = md5((new Date()).getTime().toString())
let savePath = `${object_path}${fileName}.jpeg`
wx.uploadFile({
url: host,
filePath: file.tempFilePaths[0],
name:'file',
formData:{
'key': savePath, //设置文件上传至OSS后的文件路径。例如:test/myphoto.jpg
'policy': policy,
'OSSAccessKeyId': AccessKeyId,
'signature': signature,
'x-oss-security-token': SecurityToken //使用STS签名时必传
},
success:(res)=>{
//上传成功
if(res.statusCode === 204){
//访问上传后的图片:domain+savePath
}
}
})
}
})
[官方文档地址](https://help.aliyun.com/document_detail/92883.html)