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()
}
)
}
}
})
},
密钥能放前端?
学习了
请教下上传oss时候,uploadFile 返回的 statusCode 不是204由于是偶发未截取到返回code
好用
请问 这是为什么?
如果要删除某个图片, 怎么删掉阿里云上的存储的图片
大佬,求一份引用js
加密的文件能发一份吗?谢谢
大佬可以将加密文件发我一份吗。找了几个都报错