写商城的时候,后端把原来的后端图片->服务器->oss改成了
后端图片直传oss,再把图片地址存进服务器,准备把前端也改成这样的
网上找到的一些代码不是很齐全,这里自己改了一下后,就分享出来了,返回给前端的sts数据格式如下:
accessKeyId: "STS.NTC****************6YMEEzhtnK7V" accessKeySecret: "3K77rcLct*******************GepepY5fhazYwEW" bucket: "h*****p" region: "oss-cn-beijing" stsToken: "CAIS7wF1q6Ft5B2y*****************6ctDz2IHpOeHlgBe4bsfo0lW5R6/8dlq53TJl"
前端小程序上传的封装
核心的封闭代码如下,
const uploadFile = function (filePath, dir,stsinfo, successc, failc) { if (!filePath || filePath.length < 9) { wx.showModal({ title: '图片错误', content: '请重试', showCancel: false, }) return; } let suffix = filePath.split('.').pop().toLowerCase(); //图片名字 可以自行定义, 这里是采用当前的时间戳 + 150内的随机数来给图片命名的 let filename = dir + new Date().getTime() + Math.floor(Math.random() * 150) + '.'+suffix; let aliyunServerURL = "https://"+stsinfo.bucket+"."+stsinfo.region+".aliyuncs.com";//OSS地址,需要https let accessid = stsinfo.accessKeyId; let policyBase64 = getPolicyBase64(); let signature = getSignature(policyBase64,stsinfo);//获取签名 uni.uploadFile({ url: aliyunServerURL,//开发者服务器 url filePath: filePath,//要上传文件资源的路径 name: 'file',//必须填file formData: { 'key': filename, 'policy': policyBase64, 'OSSAccessKeyId': accessid, 'signature': signature, 'x-oss-security-token': stsinfo.stsToken, 'success_action_status': '200', }, success: function (res) { if (res.statusCode != 200) { failc(new Error('上传错误:' + JSON.stringify(res))) return; } successc(aliyunServerURL+"/"+filename); }, fail: function (err) { err.wxaddinfo = aliyunServerURL; failc(err); }, }) }
完整代码可以进入阿里云sts小程序上传封装gitee
里面也有比较详细的介绍