sts-put-server-key.html 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Ajax Put 上传</title>
  6. <style>
  7. h1, h2 {
  8. font-weight: normal;
  9. }
  10. #msg {
  11. margin-top: 10px;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <h1>Ajax Put 上传</h1>
  17. <input id="fileSelector" type="file">
  18. <input id="submitBtn" type="submit">
  19. <div id="msg"></div>
  20. <script src="common/cos-auth.min.js"></script>
  21. <script>
  22. (function () {
  23. // 请求用到的参数
  24. var Bucket = 'test-1250000000';
  25. var Region = 'ap-guangzhou';
  26. var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
  27. var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';
  28. // 对更多字符编码的 url encode 格式
  29. var camSafeUrlEncode = function (str) {
  30. return encodeURIComponent(str)
  31. .replace(/!/g, '%21')
  32. .replace(/'/g, '%27')
  33. .replace(/\(/g, '%28')
  34. .replace(/\)/g, '%29')
  35. .replace(/\*/g, '%2A');
  36. };
  37. // 计算签名
  38. var getKeyAndAuth = function (options, callback) {
  39. var url = 'http://127.0.0.1:3000/sts-server-key';
  40. var xhr = new XMLHttpRequest();
  41. xhr.open('GET', url, true);
  42. xhr.onload = function (e) {
  43. var result, credentials;
  44. try {
  45. result = (new Function('return ' + xhr.responseText))();
  46. credentials = result.credentials;
  47. } catch (e) {}
  48. if (result && credentials) {
  49. callback(null, {
  50. Key: result.Key, // 这里在后端加一个字段决定上传的文件名
  51. SecurityToken: credentials.sessionToken,
  52. Authorization: CosAuth({
  53. SecretId: credentials.tmpSecretId,
  54. SecretKey: credentials.tmpSecretKey,
  55. Method: options.Method,
  56. Pathname: '/' + options.Key,
  57. }),
  58. });
  59. } else {
  60. console.error(xhr.responseText);
  61. callback('获取签名出错');
  62. }
  63. };
  64. xhr.onerror = function (e) {
  65. callback('获取签名出错');
  66. };
  67. xhr.send();
  68. };
  69. // 上传文件
  70. var uploadFile = function (file, callback) {
  71. getKeyAndAuth({Method: 'PUT', FileName: file.name}, function (err, info) {
  72. var Key = info.Key;
  73. if (err) {
  74. alert(err);
  75. return;
  76. }
  77. var auth = info.Authorization;
  78. var SecurityToken = info.SecurityToken;
  79. var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
  80. var xhr = new XMLHttpRequest();
  81. xhr.open('PUT', url, true);
  82. xhr.setRequestHeader('Authorization', auth);
  83. SecurityToken && xhr.setRequestHeader('x-cos-security-token', SecurityToken);
  84. xhr.upload.onprogress = function (e) {
  85. console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
  86. };
  87. xhr.onload = function () {
  88. if (xhr.status === 200 || xhr.status === 206) {
  89. var ETag = xhr.getResponseHeader('etag');
  90. callback(null, {url: url, ETag: ETag});
  91. } else {
  92. callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
  93. }
  94. };
  95. xhr.onerror = function () {
  96. callback('文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则');
  97. };
  98. xhr.send(file);
  99. });
  100. };
  101. // 监听表单提交
  102. document.getElementById('submitBtn').onclick = function (e) {
  103. var file = document.getElementById('fileSelector').files[0];
  104. if (!file) {
  105. document.getElementById('msg').innerText = '未选择上传文件';
  106. return;
  107. }
  108. file && uploadFile(file, function (err, data) {
  109. console.log(err || data);
  110. document.getElementById('msg').innerText = err ? err : ('上传成功,ETag=' + data.ETag);
  111. });
  112. };
  113. })();
  114. </script>
  115. </body>
  116. </html>