uoloadfile

  1. const env = require('config.js'); //配置文件,在这文件里配置你的OSS keyId和KeySecret,timeout:87600;
  2. const base64 = require('base64.js');//Base64,hmac,sha1,crypto相关算法
  3. require('hmac.js');
  4. require('sha1.js');
  5. const Crypto = require('crypto.js');
  6. /*
  7. *上传文件到阿里云oss
  8. *@param - filePath :图片的本地资源路径
  9. *@param - dir:表示要传到哪个目录下
  10. *@param - successc:成功回调
  11. *@param - failc:失败回调
  12. */
  13. const uploadFile = function (filePath, dir, successc, failc) {
  14. if (!filePath || filePath.length < 9) {
  15. wx.showModal({
  16. title: '图片错误',
  17. content: '请重试',
  18. showCancel: false,
  19. })
  20. return;
  21. }
  22. console.log('上传图片.....');
  23. //图片名字 可以自行定义, 这里是采用当前的时间戳 + 150内的随机数来给图片命名的
  24. const aliyunFileKey = dir + Math.random().toString(36).slice(-8) + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
  25. const aliyunServerURL = env.uploadImageUrl;//OSS地址,需要https
  26. const accessid = env.OSSAccessKeyId;
  27. const policyBase64 = getPolicyBase64();
  28. const signature = getSignature(policyBase64);//获取签名
  29. wx.uploadFile({
  30. url: aliyunServerURL,//开发者服务器 url
  31. filePath: filePath,//要上传文件资源的路径
  32. name: 'file',//必须填file
  33. formData: {
  34. 'key': aliyunFileKey,
  35. 'policy': policyBase64,
  36. 'OSSAccessKeyId': accessid,
  37. 'signature': signature,
  38. 'success_action_status': '200',
  39. },
  40. success: function (res) {
  41. if (res.statusCode != 200) {
  42. failc(new Error('上传错误:' + JSON.stringify(res)))
  43. return;
  44. }
  45. successc(aliyunServerURL+aliyunFileKey);
  46. },
  47. fail: function (err) {
  48. err.wxaddinfo = aliyunServerURL;
  49. failc(err);
  50. },
  51. })
  52. }
  53. const getPolicyBase64 = function () {
  54. let date = new Date();
  55. date.setHours(date.getHours() + env.timeout);
  56. let srcT = date.toISOString();
  57. const policyText = {
  58. "expiration": srcT, //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了
  59. "conditions": [
  60. ["content-length-range", 0, 10 * 1024 * 1024] // 设置上传文件的大小限制,5mb
  61. ]
  62. };
  63. const policyBase64 = base64.encode(JSON.stringify(policyText));
  64. return policyBase64;
  65. }
  66. const getSignature = function (policyBase64) {
  67. const accesskey = env.AccessKeySecret;
  68. const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
  69. asBytes: true
  70. });
  71. const signature = Crypto.util.bytesToBase64(bytes);
  72. return signature;
  73. }
  74. module.exports = uploadFile;

配置config文件

  1. var fileHost = "https://xxx.oss-cn-hangzhou.aliyuncs.com/";//你的阿里云地址最后面跟上一个/ 在你当前小程序的后台的uploadFile 合法域名也要配上这个域名
  2. var config = {
  3. //aliyun OSS config
  4. uploadImageUrl: `${fileHost}`, // 默认存在根目录,可根据需求改
  5. AccessKeySecret: 'xxxxxxxxxxxxxxx', // AccessKeySecret 去你的阿里云上控制台上找
  6. OSSAccessKeyId: 'xxxxxxxxxxx', // AccessKeyId 去你的阿里云上控制台上找
  7. timeout: 87600 //这个是上传文件时Policy的失效时间
  8. };
  9. module.exports = config

需要以下算法
base64,crypto,hmac,sha1

base64

  1. var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2. var base64DecodeChars = new Array(
  3. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  4. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  5. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
  6. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
  7. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  8. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
  9. -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  10. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
  11. function encode(str) {
  12. var out, i, len;
  13. var c1, c2, c3;
  14. len = str.length;
  15. i = 0;
  16. out = "";
  17. while (i < len) {
  18. c1 = str.charCodeAt(i++) & 0xff;
  19. if (i == len) {
  20. out += base64EncodeChars.charAt(c1 >> 2);
  21. out += base64EncodeChars.charAt((c1 & 0x3) << 4);
  22. out += "==";
  23. break;
  24. }
  25. c2 = str.charCodeAt(i++);
  26. if (i == len) {
  27. out += base64EncodeChars.charAt(c1 >> 2);
  28. out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  29. out += base64EncodeChars.charAt((c2 & 0xF) << 2);
  30. out += "=";
  31. break;
  32. }
  33. c3 = str.charCodeAt(i++);
  34. out += base64EncodeChars.charAt(c1 >> 2);
  35. out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  36. out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  37. out += base64EncodeChars.charAt(c3 & 0x3F);
  38. }
  39. return out;
  40. }
  41. function decode(str) {
  42. var c1, c2, c3, c4;
  43. var i, len, out;
  44. len = str.length;
  45. i = 0;
  46. out = "";
  47. while (i < len) {
  48. /* c1 */
  49. do {
  50. c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
  51. } while (i < len && c1 == -1);
  52. if (c1 == -1)
  53. break;
  54. /* c2 */
  55. do {
  56. c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
  57. } while (i < len && c2 == -1);
  58. if (c2 == -1)
  59. break;
  60. out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
  61. /* c3 */
  62. do {
  63. c3 = str.charCodeAt(i++) & 0xff;
  64. if (c3 == 61)
  65. return out;
  66. c3 = base64DecodeChars[c3];
  67. } while (i < len && c3 == -1);
  68. if (c3 == -1)
  69. break;
  70. out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
  71. /* c4 */
  72. do {
  73. c4 = str.charCodeAt(i++) & 0xff;
  74. if (c4 == 61)
  75. return out;
  76. c4 = base64DecodeChars[c4];
  77. } while (i < len && c4 == -1);
  78. if (c4 == -1)
  79. break;
  80. out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
  81. }
  82. return out;
  83. }
  84. function utf16to8(str) {
  85. var out, i, len, c;
  86. out = "";
  87. len = str.length;
  88. for (i = 0; i < len; i++) {
  89. c = str.charCodeAt(i);
  90. if ((c >= 0x0001) && (c <= 0x007F)) {
  91. out += str.charAt(i);
  92. } else if (c > 0x07FF) {
  93. out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
  94. out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
  95. out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
  96. } else {
  97. out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
  98. out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
  99. }
  100. }
  101. return out;
  102. }
  103. function utf8to16(str) {
  104. var out, i, len, c;
  105. var char2, char3;
  106. out = "";
  107. len = str.length;
  108. i = 0;
  109. while (i < len) {
  110. c = str.charCodeAt(i++);
  111. switch (c >> 4) {
  112. case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
  113. // 0xxxxxxx
  114. out += str.charAt(i - 1);
  115. break;
  116. case 12: case 13:
  117. // 110x xxxx 10xx xxxx
  118. char2 = str.charCodeAt(i++);
  119. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
  120. break;
  121. case 14:
  122. // 1110 xxxx 10xx xxxx 10xx xxxx
  123. char2 = str.charCodeAt(i++);
  124. char3 = str.charCodeAt(i++);
  125. out += String.fromCharCode(((c & 0x0F) << 12) |
  126. ((char2 & 0x3F) << 6) |
  127. ((char3 & 0x3F) << 0));
  128. break;
  129. }
  130. }
  131. return out;
  132. }
  133. module.exports = {
  134. encode: encode,
  135. decode: decode,
  136. utf16to8: utf16to8,
  137. utf8to16: utf8to16
  138. }

crypto

  1. const Crypto = {};
  2. (function(){
  3. var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4. // Crypto utilities
  5. var util = Crypto.util = {
  6. // Bit-wise rotate left
  7. rotl: function (n, b) {
  8. return (n << b) | (n >>> (32 - b));
  9. },
  10. // Bit-wise rotate right
  11. rotr: function (n, b) {
  12. return (n << (32 - b)) | (n >>> b);
  13. },
  14. // Swap big-endian to little-endian and vice versa
  15. endian: function (n) {
  16. // If number given, swap endian
  17. if (n.constructor == Number) {
  18. return util.rotl(n, 8) & 0x00FF00FF |
  19. util.rotl(n, 24) & 0xFF00FF00;
  20. }
  21. // Else, assume array and swap all items
  22. for (var i = 0; i < n.length; i++)
  23. n[i] = util.endian(n[i]);
  24. return n;
  25. },
  26. // Generate an array of any length of random bytes
  27. randomBytes: function (n) {
  28. for (var bytes = []; n > 0; n--)
  29. bytes.push(Math.floor(Math.random() * 256));
  30. return bytes;
  31. },
  32. // Convert a string to a byte array
  33. stringToBytes: function (str) {
  34. var bytes = [];
  35. for (var i = 0; i < str.length; i++)
  36. bytes.push(str.charCodeAt(i));
  37. return bytes;
  38. },
  39. // Convert a byte array to a string
  40. bytesToString: function (bytes) {
  41. var str = [];
  42. for (var i = 0; i < bytes.length; i++)
  43. str.push(String.fromCharCode(bytes[i]));
  44. return str.join("");
  45. },
  46. // Convert a string to big-endian 32-bit words
  47. stringToWords: function (str) {
  48. var words = [];
  49. for (var c = 0, b = 0; c < str.length; c++, b += 8)
  50. words[b >>> 5] |= str.charCodeAt(c) << (24 - b % 32);
  51. return words;
  52. },
  53. // Convert a byte array to big-endian 32-bits words
  54. bytesToWords: function (bytes) {
  55. var words = [];
  56. for (var i = 0, b = 0; i < bytes.length; i++, b += 8)
  57. words[b >>> 5] |= bytes[i] << (24 - b % 32);
  58. return words;
  59. },
  60. // Convert big-endian 32-bit words to a byte array
  61. wordsToBytes: function (words) {
  62. var bytes = [];
  63. for (var b = 0; b < words.length * 32; b += 8)
  64. bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
  65. return bytes;
  66. },
  67. // Convert a byte array to a hex string
  68. bytesToHex: function (bytes) {
  69. var hex = [];
  70. for (var i = 0; i < bytes.length; i++) {
  71. hex.push((bytes[i] >>> 4).toString(16));
  72. hex.push((bytes[i] & 0xF).toString(16));
  73. }
  74. return hex.join("");
  75. },
  76. // Convert a hex string to a byte array
  77. hexToBytes: function (hex) {
  78. var bytes = [];
  79. for (var c = 0; c < hex.length; c += 2)
  80. bytes.push(parseInt(hex.substr(c, 2), 16));
  81. return bytes;
  82. },
  83. // Convert a byte array to a base-64 string
  84. bytesToBase64: function (bytes) {
  85. // Use browser-native function if it exists
  86. if (typeof btoa == "function") return btoa(util.bytesToString(bytes));
  87. var base64 = [],
  88. overflow;
  89. for (var i = 0; i < bytes.length; i++) {
  90. switch (i % 3) {
  91. case 0:
  92. base64.push(base64map.charAt(bytes[i] >>> 2));
  93. overflow = (bytes[i] & 0x3) << 4;
  94. break;
  95. case 1:
  96. base64.push(base64map.charAt(overflow | (bytes[i] >>> 4)));
  97. overflow = (bytes[i] & 0xF) << 2;
  98. break;
  99. case 2:
  100. base64.push(base64map.charAt(overflow | (bytes[i] >>> 6)));
  101. base64.push(base64map.charAt(bytes[i] & 0x3F));
  102. overflow = -1;
  103. }
  104. }
  105. // Encode overflow bits, if there are any
  106. if (overflow != undefined && overflow != -1)
  107. base64.push(base64map.charAt(overflow));
  108. // Add padding
  109. while (base64.length % 4 != 0) base64.push("=");
  110. return base64.join("");
  111. },
  112. // Convert a base-64 string to a byte array
  113. base64ToBytes: function (base64) {
  114. // Use browser-native function if it exists
  115. if (typeof atob == "function") return util.stringToBytes(atob(base64));
  116. // Remove non-base-64 characters
  117. base64 = base64.replace(/[^A-Z0-9+\/]/ig, "");
  118. var bytes = [];
  119. for (var i = 0; i < base64.length; i++) {
  120. switch (i % 4) {
  121. case 1:
  122. bytes.push((base64map.indexOf(base64.charAt(i - 1)) << 2) |
  123. (base64map.indexOf(base64.charAt(i)) >>> 4));
  124. break;
  125. case 2:
  126. bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0xF) << 4) |
  127. (base64map.indexOf(base64.charAt(i)) >>> 2));
  128. break;
  129. case 3:
  130. bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0x3) << 6) |
  131. (base64map.indexOf(base64.charAt(i))));
  132. break;
  133. }
  134. }
  135. return bytes;
  136. }
  137. };
  138. // Crypto mode namespace
  139. Crypto.mode = {};
  140. })();
  141. module.exports = Crypto;

hmac

  1. const Crypto = require('./crypto.js');
  2. (function(){
  3. // Shortcut
  4. var util = Crypto.util;
  5. Crypto.HMAC = function (hasher, message, key, options) {
  6. // Allow arbitrary length keys
  7. key = key.length > hasher._blocksize * 4 ?
  8. hasher(key, { asBytes: true }) :
  9. util.stringToBytes(key);
  10. // XOR keys with pad constants
  11. var okey = key,
  12. ikey = key.slice(0);
  13. for (var i = 0; i < hasher._blocksize * 4; i++) {
  14. okey[i] ^= 0x5C;
  15. ikey[i] ^= 0x36;
  16. }
  17. var hmacbytes = hasher(util.bytesToString(okey) +
  18. hasher(util.bytesToString(ikey) + message, { asString: true }),
  19. { asBytes: true });
  20. return options && options.asBytes ? hmacbytes :
  21. options && options.asString ? util.bytesToString(hmacbytes) :
  22. util.bytesToHex(hmacbytes);
  23. };
  24. })();
  25. module.exports = Crypto;

sha1

  1. const Crypto = require('./crypto.js');
  2. (function(){
  3. // Shortcut
  4. var util = Crypto.util;
  5. // Public API
  6. var SHA1 = Crypto.SHA1 = function (message, options) {
  7. var digestbytes = util.wordsToBytes(SHA1._sha1(message));
  8. return options && options.asBytes ? digestbytes :
  9. options && options.asString ? util.bytesToString(digestbytes) :
  10. util.bytesToHex(digestbytes);
  11. };
  12. // The core
  13. SHA1._sha1 = function (message) {
  14. var m = util.stringToWords(message),
  15. l = message.length * 8,
  16. w = [],
  17. H0 = 1732584193,
  18. H1 = -271733879,
  19. H2 = -1732584194,
  20. H3 = 271733878,
  21. H4 = -1009589776;
  22. // Padding
  23. m[l >> 5] |= 0x80 << (24 - l % 32);
  24. m[((l + 64 >>> 9) << 4) + 15] = l;
  25. for (var i = 0; i < m.length; i += 16) {
  26. var a = H0,
  27. b = H1,
  28. c = H2,
  29. d = H3,
  30. e = H4;
  31. for (var j = 0; j < 80; j++) {
  32. if (j < 16) w[j] = m[i + j];
  33. else {
  34. var n = w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16];
  35. w[j] = (n << 1) | (n >>> 31);
  36. }
  37. var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
  38. j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
  39. j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
  40. j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
  41. (H1 ^ H2 ^ H3) - 899497514);
  42. H4 = H3;
  43. H3 = H2;
  44. H2 = (H1 << 30) | (H1 >>> 2);
  45. H1 = H0;
  46. H0 = t;
  47. }
  48. H0 += a;
  49. H1 += b;
  50. H2 += c;
  51. H3 += d;
  52. H4 += e;
  53. }
  54. return [H0, H1, H2, H3, H4];
  55. };
  56. // Package private blocksize
  57. SHA1._blocksize = 16;
  58. })();
  59. module.exports = Crypto;