1.首先创建oss密钥 这里我新建了一个名字 命名为config.js
var fileHost = "https://*****************/";
var config = {
uploadImageUrl: `${fileHost}`,
AccessKeySecret: '*******',
OSSAccessKeyId: '********',
timeout: 87600
};
module.exports = config
2.创建上传配置文件 我这里命名为upload.js
const env = require('config.js');
const base64 = require('base64.js');
require('hmac.js');
require('sha1.js');
const Crypto = require('crypto.js');
const uploadFile = function (filePath, dir, successc, failc) {
if (!filePath || filePath.length < 9) {
wx.showModal({
title: '图片错误',
content: '请重试',
showCancel: false,
})
return;
}
console.log('上传图片.....');
console.log(dir)
const aliyunFileKey = dir+ new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
const aliyunServerURL = env.uploadImageUrl;
const accessid = env.OSSAccessKeyId;
const policyBase64 = getPolicyBase64();
const signature = getSignature(policyBase64);
console.log(env)
wx.uploadFile({
url: aliyunServerURL,
filePath: filePath,
name: 'file',
formData: {
'key': aliyunFileKey,
'policy': policyBase64,
'OSSAccessKeyId': accessid,
'signature': signature,
'success_action_status': '200',
},
success: function (res) {
console.log(res)
if (res.statusCode != 200) {
failc(new Error('上传错误:' + JSON.stringify(res)))
return;
}
successc(aliyunServerURL+aliyunFileKey);
},
fail: function (err) {
err.wxaddinfo = aliyunServerURL;
failc(err);
},
})
}
const getPolicyBase64 = function () {
let date = new Date();
date.setHours(date.getHours() + env.timeout);
let srcT = date.toISOString();
const policyText = {
"expiration": srcT,
"conditions": [
["content-length-range", 0, 5 * 1024 * 1024]
]
};
const policyBase64 = base64.encode(JSON.stringify(policyText));
return policyBase64;
}
const getSignature = function (policyBase64) {
const accesskey = env.AccessKeySecret;
const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
asBytes: true
});
const signature = Crypto.util.bytesToBase64(bytes);
return signature;
}
module.exports = uploadFile;
3.小程序页面调用的时候
const uploadImage = require('../../utils/upload');
uploadImage() {
let that = this;
let applyRefundImgList = that.data.applyRefundImgList
wx.chooseImage({
count: 5 - applyRefundImgList.length,
success: function(res) {
wx.showLoading({
title: '上传中',
mask: true
})
for (let index = 0; index < res.tempFilePaths.length; index++) {
uploadImage(res.tempFilePaths[index], `applyrefund/${shopUuid}/`,
function(res) {
wx.hideLoading()
applyRefundImgList.push(res)
that.setData({
applyRefundImgList
})
},
function(res) {
wx.hideLoading()
}
)
}
}
})
},
你好,能发我一份引用的文件吗,base64.js和crypto.js的 const base64 = require('base64.js');//Base64,hmac,sha1,crypto相关算法 const Crypto = require('crypto.js');
你好,引用的文件可以发我一份吗
小写post 为什么不行
你好,可以把引用的文件也发我一份吗?我百度了一会,但是没有找到。
阿里云文档里有个oss上传回调 怎么操作
successc是上传成功的回调,failc是上传失败的回调
你好,我也在做小程序上传oss视频,能把引用的文件发我一份吗?获取签名那里总是报错
你好 请问这个需要引入什么文件吗?
这个报错是什么原因呀?
我的阿里云oss地址是http格式的 没法在后台配置upload合法域名
最好还是由服务端生成签名去使用吧