form_sts.html 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Form 表单简单上传(兼容 IE8)(前端计算签名)</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>Form 表单简单上传(兼容 IE8)(前端计算签名)</h1>
  18. <div>最低兼容到 IE6 上传,不支持 onprogress</div>
  19. <form
  20. id="form"
  21. target="submitTarget"
  22. action=""
  23. method="post"
  24. enctype="multipart/form-data"
  25. accept="*/*"
  26. >
  27. <input id="name" name="name" type="hidden" value="" />
  28. <input name="success_action_status" type="hidden" value="200" />
  29. <input
  30. id="success_action_redirect"
  31. name="success_action_redirect"
  32. type="hidden"
  33. value=""
  34. />
  35. <input id="key" name="key" type="hidden" value="" />
  36. <input id="policy" name="policy" type="hidden" value="" />
  37. <input
  38. id="q-sign-algorithm"
  39. name="q-sign-algorithm"
  40. type="hidden"
  41. value=""
  42. />
  43. <input id="q-ak" name="q-ak" type="hidden" value="" />
  44. <input id="q-key-time" name="q-key-time" type="hidden" value="" />
  45. <input id="q-signature" name="q-signature" type="hidden" value="" />
  46. <input name="Content-Type" type="hidden" value="" />
  47. <input
  48. id="x-cos-security-token"
  49. name="x-cos-security-token"
  50. type="hidden"
  51. value=""
  52. />
  53. <!-- file 字段放在表单最后,避免文件内容过长影响签名判断和鉴权 -->
  54. <input id="fileSelector" name="file" type="file" />
  55. <input id="submitBtn" type="button" value="提交" />
  56. </form>
  57. <iframe
  58. id="submitTarget"
  59. name="submitTarget"
  60. style="display: none"
  61. frameborder="0"
  62. ></iframe>
  63. <div id="msg"></div>
  64. <!-- 签名计算 可通过(https://unpkg.com/cos-js-sdk-v5/demo/common/cos-auth.min.js)下载 -->
  65. <script src="../common/cos-auth.js"></script>
  66. <script>
  67. (function () {
  68. // 请求用到的参数
  69. const Bucket = 'examplebucket-1250000000'; // 替换为自己的存储桶
  70. const Region = 'ap-beijing'; // 替换为自己的存储桶地域
  71. const protocol = location.protocol === 'https:' ? 'https:' : 'http:';
  72. const prefix =
  73. protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com'; // prefix 用于拼接请求
  74. const form = document.getElementById('form');
  75. form.action = prefix;
  76. // 对更多字符编码的 url encode 格式
  77. const camSafeUrlEncode = function (str) {
  78. return encodeURIComponent(str)
  79. .replace(/!/g, '%21')
  80. .replace(/'/g, '%27')
  81. .replace(/\(/g, '%28')
  82. .replace(/\)/g, '%29')
  83. .replace(/\*/g, '%2A');
  84. };
  85. // 计算签名
  86. const getAuthorization = function (opt, callback) {
  87. // 替换为自己服务端地址 获取临时密钥
  88. const url = `http://127.0.0.1:3000/sts`;
  89. const xhr = new XMLHttpRequest();
  90. xhr.open('GET', url, true);
  91. xhr.onload = function (e) {
  92. let result;
  93. try {
  94. result = JSON.parse(e.target.responseText);
  95. } catch (e) {
  96. callback('获取签名出错');
  97. }
  98. if (result) {
  99. // 使用CosAuth 利用返回的临时密钥计算签名
  100. const policyInfo = CosAuth({
  101. Version: 'post-object-policy', // 必传 写死 用于post签名计算
  102. SecretId: result.credentials.tmpSecretId,
  103. SecretKey: result.credentials.tmpSecretKey,
  104. Bucket,
  105. Key: opt.Key,
  106. });
  107. callback(null, {
  108. securityToken: result.credentials.securityToken,
  109. policyInfo: policyInfo,
  110. });
  111. } else {
  112. console.error(xhr.responseText);
  113. callback('获取签名出错');
  114. }
  115. };
  116. xhr.send();
  117. };
  118. // 监听上传完成
  119. let Key;
  120. const submitTarget = document.getElementById('submitTarget');
  121. const showMessage = function (err, data) {
  122. console.log(err || data);
  123. document.getElementById('msg').innerText = err
  124. ? err
  125. : '上传成功,ETag=' + data.ETag;
  126. };
  127. submitTarget.onload = function () {
  128. let search;
  129. try {
  130. search = submitTarget.contentWindow.location.search.substr(1);
  131. } catch (e) {
  132. showMessage('文件 ' + Key + ' 上传失败');
  133. }
  134. if (search) {
  135. const items = search.split('&');
  136. let i = 0;
  137. let arr = [];
  138. const data = {};
  139. for (i = 0; i < items.length; i++) {
  140. arr = items[i].split('=');
  141. data[arr[0]] = decodeURIComponent(arr[1] || '');
  142. }
  143. showMessage(null, {
  144. url: prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/'),
  145. ETag: data.etag,
  146. });
  147. } else {
  148. }
  149. };
  150. // 发起上传
  151. document.getElementById('submitBtn').onclick = function (e) {
  152. const file = document.getElementById('fileSelector').files[0];
  153. if (!file) {
  154. document.getElementById('msg').innerText = '未选择上传文件';
  155. return;
  156. }
  157. Key = file.name;
  158. getAuthorization({ Key }, function (err, AuthData) {
  159. if (err) {
  160. alert(err);
  161. return;
  162. }
  163. // 在当前目录下放一个空的 empty.html 以便让接口上传完成跳转回来
  164. document.getElementById('success_action_redirect').value =
  165. location.href.substr(0, location.href.lastIndexOf('/') + 1) +
  166. 'empty.html';
  167. document.getElementById('key').value = Key;
  168. document.getElementById('policy').value =
  169. AuthData.policyInfo.policy;
  170. document.getElementById('q-sign-algorithm').value =
  171. AuthData.policyInfo.qSignAlgorithm;
  172. document.getElementById('q-ak').value = AuthData.policyInfo.qAk;
  173. document.getElementById('q-key-time').value =
  174. AuthData.policyInfo.qKeyTime;
  175. document.getElementById('q-signature').value =
  176. AuthData.policyInfo.qSignature;
  177. document.getElementById('x-cos-security-token').value =
  178. AuthData.securityToken || '';
  179. form.submit();
  180. });
  181. };
  182. })();
  183. </script>
  184. </body>
  185. </html>