uploadFile.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. uni.showModal({
  16. title: '图片错误',
  17. content: '请重试',
  18. showCancel: false,
  19. })
  20. return;
  21. }
  22. //图片名字 可以自行定义, 这里是采用当前的时间戳 + 150内的随机数来给图片命名的
  23. const aliyunFileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
  24. const aliyunServerURL = env.uploadImageUrl;//OSS地址,需要https
  25. const accessid = env.OSSAccessKeyId;
  26. const policyBase64 = getPolicyBase64();
  27. const signature = getSignature(policyBase64);//获取签名
  28. uni.uploadFile({
  29. url: aliyunServerURL,//开发者服务器 url
  30. filePath: filePath,//要上传文件资源的路径
  31. name: 'file',//必须填file
  32. formData: {
  33. 'key': aliyunFileKey,
  34. 'policy': policyBase64,
  35. 'OSSAccessKeyId': accessid,
  36. 'signature': signature,
  37. 'success_action_status': '200',
  38. },
  39. success: function (res) {
  40. console.log(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, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
  61. ]
  62. };
  63. const policyBase64 = base64.encode(JSON.stringify(policyText));
  64. console.log(policyBase64);
  65. return policyBase64;
  66. }
  67. const getSignature = function (policyBase64) {
  68. const accesskey = env.AccessKeySecret;
  69. const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
  70. asBytes: true
  71. });
  72. const signature = Crypto.util.bytesToBase64(bytes);
  73. console.log(signature);
  74. return signature;
  75. }
  76. module.exports = uploadFile;