1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| 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('上传图片…'); const aliyunFileKey = dir+filePath.replace('wxfile://', '');
const aliyunServerURL = env.uploadImageUrl; const accessid = env.OSSAccessKeyId; const policyBase64 = getPolicyBase64(); const signature = getSignature(policyBase64);
console.log('aliyunFileKey=', aliyunFileKey); console.log('aliyunServerURL',aliyunServerURL); wx.uploadFile({ url: aliyunServerURL, filePath: filePath, name: 'file',//必须填file formData: { 'key': aliyunFileKey, 'policy': policyBase64, 'OSSAccessKeyId': accessid, 'signature': signature, 'success_action_status': '200', }, success: function (res) { if (res.statusCode != 200) { failc(new Error('上传错误:' + JSON.stringify(res))) return; } console.log('上传图片成功', res) successc(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;
|