form_sign.html 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. <script>
  65. (function () {
  66. const form = document.getElementById('form');
  67. let prefix = '';
  68. // 对更多字符编码的 url encode 格式
  69. const camSafeUrlEncode = function (str) {
  70. return encodeURIComponent(str)
  71. .replace(/!/g, '%21')
  72. .replace(/'/g, '%27')
  73. .replace(/\(/g, '%28')
  74. .replace(/\)/g, '%29')
  75. .replace(/\*/g, '%2A');
  76. };
  77. // 计算签名
  78. const getAuthorization = function (opt, callback) {
  79. // 替换为自己服务端地址 获取post上传签名
  80. const url = `http://127.0.0.1:3000/post-policy?ext=${opt.ext || ''}`;
  81. const xhr = new XMLHttpRequest();
  82. xhr.open('GET', url, true);
  83. xhr.onload = function (e) {
  84. let credentials;
  85. try {
  86. const result = JSON.parse(e.target.responseText);
  87. credentials = result;
  88. } catch (e) {
  89. callback('获取签名出错');
  90. }
  91. if (credentials) {
  92. callback(null, {
  93. securityToken: credentials.securityToken,
  94. cosKey: credentials.cosKey,
  95. cosHost: credentials.cosHost,
  96. policy: credentials.policy,
  97. qAk: credentials.qAk,
  98. qKeyTime: credentials.qKeyTime,
  99. qSignAlgorithm: credentials.qSignAlgorithm,
  100. qSignature: credentials.qSignature,
  101. });
  102. } else {
  103. console.error(xhr.responseText);
  104. callback('获取签名出错');
  105. }
  106. };
  107. xhr.send();
  108. };
  109. // 监听上传完成
  110. let Key;
  111. const submitTarget = document.getElementById('submitTarget');
  112. const showMessage = function (err, data) {
  113. console.log(err || data);
  114. document.getElementById('msg').innerText = err
  115. ? err
  116. : '上传成功,ETag=' + data.ETag;
  117. };
  118. submitTarget.onload = function () {
  119. let search;
  120. try {
  121. search = submitTarget.contentWindow.location.search.substr(1);
  122. } catch (e) {
  123. showMessage('文件 ' + Key + ' 上传失败');
  124. }
  125. if (search) {
  126. const items = search.split('&');
  127. let i = 0;
  128. let arr = [];
  129. const data = {};
  130. for (i = 0; i < items.length; i++) {
  131. arr = items[i].split('=');
  132. data[arr[0]] = decodeURIComponent(arr[1] || '');
  133. }
  134. showMessage(null, {
  135. url: prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/'),
  136. ETag: data.etag,
  137. });
  138. } else {
  139. }
  140. };
  141. // 发起上传
  142. document.getElementById('submitBtn').onclick = function (e) {
  143. const filePath = document.getElementById('fileSelector').value;
  144. if (!filePath) {
  145. document.getElementById('msg').innerText = '未选择上传文件';
  146. return;
  147. }
  148. let ext = '';
  149. const lastDotIndex = filePath.lastIndexOf('.');
  150. if (lastDotIndex > -1) {
  151. // 这里获取文件后缀 由服务端生成最终上传的路径
  152. ext = filePath.substring(lastDotIndex + 1);
  153. }
  154. getAuthorization({ ext }, function (err, AuthData) {
  155. if (err) {
  156. alert(err);
  157. return;
  158. }
  159. const protocol =
  160. location.protocol === 'https:' ? 'https:' : 'http:';
  161. prefix = protocol + '//' + AuthData.cosHost;
  162. form.action = prefix;
  163. Key = AuthData.cosKey;
  164. // 在当前目录下放一个空的 empty.html 以便让接口上传完成跳转回来
  165. document.getElementById('success_action_redirect').value =
  166. location.href.substr(0, location.href.lastIndexOf('/') + 1) +
  167. 'empty.html';
  168. document.getElementById('key').value = AuthData.cosKey;
  169. document.getElementById('policy').value = AuthData.policy;
  170. document.getElementById('q-sign-algorithm').value =
  171. AuthData.qSignAlgorithm;
  172. document.getElementById('q-ak').value = AuthData.qAk;
  173. document.getElementById('q-key-time').value = AuthData.qKeyTime;
  174. document.getElementById('q-signature').value = AuthData.qSignature;
  175. document.getElementById('x-cos-security-token').value =
  176. AuthData.securityToken || '';
  177. form.submit();
  178. });
  179. };
  180. })();
  181. </script>
  182. </body>
  183. </html>