post_sts.html 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Ajax Post 上传(前端计算签名)</title>
  6. <style>
  7. h1,
  8. h2 {
  9. font-weight: normal;
  10. }
  11. #msg {
  12. margin-top: 10px;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <h1>PostObject 上传(前端计算签名)</h1>
  18. <input id="fileSelector" type="file" />
  19. <input id="submitBtn" type="submit" />
  20. <div id="msg"></div>
  21. <!-- 签名计算 可通过(https://unpkg.com/cos-js-sdk-v5/demo/common/cos-auth.min.js)下载 -->
  22. <script src="../common/cos-auth.js"></script>
  23. <script>
  24. (function () {
  25. // 请求用到的参数
  26. const Bucket = 'examplebucket-1250000000'; // 替换为自己的存储桶
  27. const Region = 'ap-beijing'; // 替换为自己的存储桶地域
  28. const protocol = location.protocol === 'https:' ? 'https:' : 'http:';
  29. const prefix =
  30. protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com'; // prefix 用于拼接请求
  31. // 对更多字符编码的 url encode 格式
  32. const camSafeUrlEncode = function (str) {
  33. return encodeURIComponent(str)
  34. .replace(/!/g, '%21')
  35. .replace(/'/g, '%27')
  36. .replace(/\(/g, '%28')
  37. .replace(/\)/g, '%29')
  38. .replace(/\*/g, '%2A');
  39. };
  40. // 获取权限策略
  41. const getAuthorization = function (opt, callback) {
  42. // 替换为自己服务端地址 获取临时密钥
  43. const url = `http://127.0.0.1:3000/sts`;
  44. const xhr = new XMLHttpRequest();
  45. xhr.open('GET', url, true);
  46. xhr.onload = function (e) {
  47. let result;
  48. try {
  49. result = JSON.parse(e.target.responseText);
  50. } catch (e) {
  51. callback('获取签名出错');
  52. }
  53. if (result) {
  54. // 使用CosAuth利用返回的临时密钥计算签名
  55. const policyInfo = CosAuth({
  56. Version: 'post-object-policy', // 必传 写死 用于post签名计算
  57. SecretId: result.credentials.tmpSecretId,
  58. SecretKey: result.credentials.tmpSecretKey,
  59. Bucket,
  60. Key: opt.Key,
  61. });
  62. callback(null, {
  63. securityToken: result.credentials.securityToken,
  64. policyInfo: policyInfo,
  65. });
  66. } else {
  67. console.error(xhr.responseText);
  68. callback('获取签名出错');
  69. }
  70. };
  71. xhr.send();
  72. };
  73. // 上传文件
  74. const uploadFile = function (file, callback) {
  75. const Key = file.name;
  76. getAuthorization({ Key }, function (err, credentials) {
  77. if (err) {
  78. alert(err);
  79. return;
  80. }
  81. const fd = new FormData();
  82. // 在当前目录下放一个空的 empty.html 以便让接口上传完成跳转回来
  83. fd.append('key', Key);
  84. // 使用 policy 签名保护格式
  85. credentials.securityToken &&
  86. fd.append('x-cos-security-token', credentials.securityToken);
  87. fd.append(
  88. 'q-sign-algorithm',
  89. credentials.policyInfo.qSignAlgorithm
  90. );
  91. fd.append('q-ak', credentials.policyInfo.qAk);
  92. fd.append('q-key-time', credentials.policyInfo.qKeyTime);
  93. fd.append('q-signature', credentials.policyInfo.qSignature);
  94. fd.append('policy', credentials.policyInfo.policy);
  95. // 文件内容,file 字段放在表单最后,避免文件内容过长影响签名判断和鉴权
  96. fd.append('file', file);
  97. // xhr
  98. const url = prefix;
  99. const xhr = new XMLHttpRequest();
  100. xhr.open('POST', url, true);
  101. xhr.upload.onprogress = function (e) {
  102. console.log(
  103. '上传进度 ' +
  104. Math.round((e.loaded / e.total) * 10000) / 100 +
  105. '%'
  106. );
  107. };
  108. xhr.onload = function () {
  109. if (Math.floor(xhr.status / 100) === 2) {
  110. const ETag = xhr.getResponseHeader('etag');
  111. callback(null, {
  112. url:
  113. prefix + '/' + camSafeUrlEncode(Key).replace(/%2F/g, '/'),
  114. ETag: ETag,
  115. });
  116. } else {
  117. callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
  118. }
  119. };
  120. xhr.onerror = function () {
  121. callback(
  122. '文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则'
  123. );
  124. };
  125. xhr.send(fd);
  126. });
  127. };
  128. // 监听表单提交
  129. document.getElementById('submitBtn').onclick = function (e) {
  130. const file = document.getElementById('fileSelector').files[0];
  131. if (!file) {
  132. document.getElementById('msg').innerText = '未选择上传文件';
  133. return;
  134. }
  135. file &&
  136. uploadFile(file, function (err, data) {
  137. console.log(err || data);
  138. document.getElementById('msg').innerText = err
  139. ? err
  140. : '上传成功,ETag=' + data.ETag + 'url=' + data.url;
  141. });
  142. };
  143. })();
  144. </script>
  145. </body>
  146. </html>