sts-put.html 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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 getAuthorization = function (options, callback) {
  39. // var url = 'http://127.0.0.1:3000/sts-auth';
  40. var url = '../server/sts.php';
  41. var xhr = new XMLHttpRequest();
  42. xhr.open('GET', url, true);
  43. xhr.onload = function (e) {
  44. var credentials;
  45. try {
  46. credentials = (new Function('return ' + xhr.responseText))().credentials;
  47. } catch (e) {}
  48. if (credentials) {
  49. callback(null, {
  50. SecurityToken: credentials.sessionToken,
  51. Authorization: CosAuth({
  52. SecretId: credentials.tmpSecretId,
  53. SecretKey: credentials.tmpSecretKey,
  54. Method: options.Method,
  55. Pathname: options.Pathname,
  56. })
  57. });
  58. } else {
  59. console.error(xhr.responseText);
  60. callback('获取签名出错');
  61. }
  62. };
  63. xhr.onerror = function (e) {
  64. callback('获取签名出错');
  65. };
  66. xhr.send();
  67. };
  68. // 上传文件
  69. var uploadFile = function (file, callback) {
  70. var Key = 'dir/' + file.name; // 这里指定上传目录和文件名
  71. getAuthorization({Method: 'PUT', Pathname: '/' + Key}, function (err, info) {
  72. if (err) {
  73. alert(err);
  74. return;
  75. }
  76. var auth = info.Authorization;
  77. var SecurityToken = info.SecurityToken;
  78. var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
  79. var xhr = new XMLHttpRequest();
  80. xhr.open('PUT', url, true);
  81. xhr.setRequestHeader('Authorization', auth);
  82. SecurityToken && xhr.setRequestHeader('x-cos-security-token', SecurityToken);
  83. xhr.upload.onprogress = function (e) {
  84. console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
  85. };
  86. xhr.onload = function () {
  87. if (xhr.status === 200 || xhr.status === 206) {
  88. var ETag = xhr.getResponseHeader('etag');
  89. callback(null, {url: url, ETag: ETag});
  90. } else {
  91. callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
  92. }
  93. };
  94. xhr.onerror = function () {
  95. callback('文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则');
  96. };
  97. xhr.send(file);
  98. });
  99. };
  100. // 监听表单提交
  101. document.getElementById('submitBtn').onclick = function (e) {
  102. var file = document.getElementById('fileSelector').files[0];
  103. if (!file) {
  104. document.getElementById('msg').innerText = '未选择上传文件';
  105. return;
  106. }
  107. file && uploadFile(file, function (err, data) {
  108. console.log(err || data);
  109. document.getElementById('msg').innerText = err ? err : ('上传成功,ETag=' + data.ETag);
  110. });
  111. };
  112. })();
  113. </script>
  114. </body>
  115. </html>