demo-no-sdk.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. var CosAuth = require('./lib/cos-auth');
  2. var config = require('./config');
  3. var uploadFile = function () {
  4. // 请求用到的参数
  5. // var prefix = 'https://cos.' + config.Region + '.myqcloud.com/' + config.Bucket + '/'; // 这个是后缀式,签名也要指定 Pathname: '/' + config.Bucket + '/'
  6. var prefix = 'https://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com/';
  7. // 对更多字符编码的 url encode 格式
  8. var camSafeUrlEncode = function (str) {
  9. return encodeURIComponent(str)
  10. .replace(/!/g, '%21')
  11. .replace(/'/g, '%27')
  12. .replace(/\(/g, '%28')
  13. .replace(/\)/g, '%29')
  14. .replace(/\*/g, '%2A');
  15. };
  16. // 获取临时密钥
  17. var stsCache;
  18. var getCredentials = function (callback) {
  19. if (stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
  20. callback(stsCache.credentials);
  21. return;
  22. }
  23. wx.request({
  24. method: 'GET',
  25. url: config.stsUrl, // 服务端签名,参考 server 目录下的两个签名例子
  26. dataType: 'json',
  27. success: function (result) {
  28. var data = result.data;
  29. var credentials = data.credentials;
  30. if (credentials) {
  31. stsCache = data
  32. } else {
  33. wx.showModal({title: '临时密钥获取失败', content: JSON.stringify(data), showCancel: false});
  34. }
  35. callback(stsCache && stsCache.credentials);
  36. },
  37. error: function (err) {
  38. wx.showModal({title: '临时密钥获取失败', content: JSON.stringify(err), showCancel: false});
  39. }
  40. });
  41. };
  42. // 计算签名
  43. var getAuthorization = function (options, callback) {
  44. getCredentials(function (credentials) {
  45. callback({
  46. XCosSecurityToken: credentials.sessionToken,
  47. Authorization: CosAuth({
  48. SecretId: credentials.tmpSecretId,
  49. SecretKey: credentials.tmpSecretKey,
  50. Method: options.Method,
  51. Pathname: options.Pathname,
  52. })
  53. });
  54. });
  55. };
  56. // 上传文件
  57. var uploadFile = function (filePath) {
  58. var Key = filePath.substr(filePath.lastIndexOf('/') + 1); // 这里指定上传的文件名
  59. getAuthorization({Method: 'POST', Pathname: '/'}, function (AuthData) {
  60. var requestTask = wx.uploadFile({
  61. url: prefix,
  62. name: 'file',
  63. filePath: filePath,
  64. formData: {
  65. 'key': Key,
  66. 'success_action_status': 200,
  67. 'Signature': AuthData.Authorization,
  68. 'x-cos-security-token': AuthData.XCosSecurityToken,
  69. 'Content-Type': '',
  70. },
  71. success: function (res) {
  72. var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
  73. if (res.statusCode === 200) {
  74. wx.showModal({title: '上传成功', content: url, showCancel: false});
  75. } else {
  76. wx.showModal({title: '上传失败', content: JSON.stringify(res), showCancel: false});
  77. }
  78. console.log(res.statusCode);
  79. console.log(url);
  80. },
  81. fail: function (res) {
  82. wx.showModal({title: '上传失败', content: JSON.stringify(res), showCancel: false});
  83. }
  84. });
  85. requestTask.onProgressUpdate(function (res) {
  86. console.log('正在进度:', res);
  87. });
  88. });
  89. };
  90. // 选择文件
  91. wx.chooseImage({
  92. count: 1, // 默认9
  93. sizeType: ['original'], // 可以指定是原图还是压缩图,这里默认用原图
  94. sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  95. success: function (res) {
  96. uploadFile(res.tempFiles[0].path);
  97. }
  98. })
  99. };
  100. module.exports = uploadFile;