post_sign.html 5.2 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. <script>
  22. (function () {
  23. let prefix = '';
  24. let Key = '';
  25. // 对更多字符编码的 url encode 格式
  26. const camSafeUrlEncode = function (str) {
  27. return encodeURIComponent(str)
  28. .replace(/!/g, '%21')
  29. .replace(/'/g, '%27')
  30. .replace(/\(/g, '%28')
  31. .replace(/\)/g, '%29')
  32. .replace(/\*/g, '%2A');
  33. };
  34. // 获取权限策略
  35. const getAuthorization = function (opt, callback) {
  36. // 替换为自己服务端地址 获取post上传签名
  37. const url = `http://127.0.0.1:3000/post-policy?ext=${opt.ext}`;
  38. const xhr = new XMLHttpRequest();
  39. xhr.open('GET', url, true);
  40. xhr.onload = function (e) {
  41. let credentials;
  42. try {
  43. const result = JSON.parse(e.target.responseText);
  44. credentials = result;
  45. } catch (e) {
  46. callback('获取签名出错');
  47. }
  48. if (credentials) {
  49. callback(null, {
  50. securityToken: credentials.securityToken,
  51. cosKey: credentials.cosKey,
  52. cosHost: credentials.cosHost,
  53. policy: credentials.policy,
  54. qAk: credentials.qAk,
  55. qKeyTime: credentials.qKeyTime,
  56. qSignAlgorithm: credentials.qSignAlgorithm,
  57. qSignature: credentials.qSignature,
  58. });
  59. } else {
  60. console.error(xhr.responseText);
  61. callback('获取签名出错');
  62. }
  63. };
  64. xhr.send();
  65. };
  66. // 上传文件
  67. const uploadFile = function (file, callback) {
  68. const fileName = file.name;
  69. let ext = '';
  70. const lastDotIndex = fileName.lastIndexOf('.');
  71. if (lastDotIndex > -1) {
  72. // 这里获取文件后缀 由服务端生成最终上传的路径
  73. ext = fileName.substring(lastDotIndex + 1);
  74. }
  75. getAuthorization({ ext }, function (err, credentials) {
  76. if (err) {
  77. alert(err);
  78. return;
  79. }
  80. const protocol =
  81. location.protocol === 'https:' ? 'https:' : 'http:';
  82. prefix = protocol + '//' + credentials.cosHost;
  83. Key = credentials.cosKey;
  84. const fd = new FormData();
  85. // 在当前目录下放一个空的 empty.html 以便让接口上传完成跳转回来
  86. fd.append('key', Key);
  87. // 使用 policy 签名保护格式
  88. credentials.securityToken &&
  89. fd.append('x-cos-security-token', credentials.securityToken);
  90. fd.append('q-sign-algorithm', credentials.qSignAlgorithm);
  91. fd.append('q-ak', credentials.qAk);
  92. fd.append('q-key-time', credentials.qKeyTime);
  93. fd.append('q-signature', credentials.qSignature);
  94. fd.append('policy', credentials.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>