put_sts.html 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Ajax Put 上传(前端计算签名)</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>Ajax Put 上传(前端计算签名)</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 = 'test-1300555317'; // 替换为自己的存储桶
  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 authorization = CosAuth({
  56. SecretId: result.credentials.tmpSecretId,
  57. SecretKey: result.credentials.tmpSecretKey,
  58. Method: opt.Method,
  59. Pathname: opt.Pathname,
  60. });
  61. callback(null, {
  62. securityToken: result.credentials.securityToken,
  63. authorization: authorization,
  64. });
  65. } else {
  66. console.error(xhr.responseText);
  67. callback('获取签名出错');
  68. }
  69. };
  70. xhr.onerror = function (e) {
  71. callback('获取签名出错');
  72. };
  73. xhr.send();
  74. };
  75. // 上传文件
  76. const uploadFile = function (file, callback) {
  77. const Key = file.name;
  78. getAuthorization(
  79. { Method: 'PUT', Pathname: '/' + Key },
  80. function (err, info) {
  81. if (err) {
  82. alert(err);
  83. return;
  84. }
  85. const auth = info.authorization;
  86. const securityToken = info.securityToken;
  87. const url =
  88. prefix + '/' + camSafeUrlEncode(Key).replace(/%2F/g, '/');
  89. const xhr = new XMLHttpRequest();
  90. xhr.open('PUT', url, true);
  91. xhr.setRequestHeader('authorization', auth);
  92. securityToken &&
  93. xhr.setRequestHeader('x-cos-security-token', securityToken);
  94. xhr.upload.onprogress = function (e) {
  95. console.log(
  96. '上传进度 ' +
  97. Math.round((e.loaded / e.total) * 10000) / 100 +
  98. '%'
  99. );
  100. };
  101. xhr.onload = function () {
  102. if (/^2\d\d$/.test('' + xhr.status)) {
  103. const ETag = xhr.getResponseHeader('etag');
  104. callback(null, { url: url, ETag: ETag });
  105. } else {
  106. callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
  107. }
  108. };
  109. xhr.onerror = function () {
  110. callback(
  111. '文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则'
  112. );
  113. };
  114. xhr.send(file);
  115. }
  116. );
  117. };
  118. // 监听表单提交
  119. document.getElementById('submitBtn').onclick = function (e) {
  120. const file = document.getElementById('fileSelector').files[0];
  121. if (!file) {
  122. document.getElementById('msg').innerText = '未选择上传文件';
  123. return;
  124. }
  125. file &&
  126. uploadFile(file, function (err, data) {
  127. console.log(err || data);
  128. document.getElementById('msg').innerText = err
  129. ? err
  130. : '上传成功,ETag=' + data.ETag + 'url=' + data.url;
  131. });
  132. };
  133. })();
  134. </script>
  135. </body>
  136. </html>