sts-post.html 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Ajax Post 上传</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 Post 上传</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';
  40. var url = '../server/sts.php';
  41. var xhr = new XMLHttpRequest();
  42. xhr.open('GET', url, true);
  43. xhr.onreadystatechange = function (e) {
  44. if (xhr.readyState === 4) {
  45. if (xhr.status === 200) {
  46. var credentials;
  47. try {
  48. credentials = (new Function('return ' + xhr.responseText))().credentials;
  49. } catch (e) {}
  50. if (credentials) {
  51. callback(null, {
  52. XCosSecurityToken: credentials.sessionToken,
  53. Authorization: CosAuth({
  54. SecretId: credentials.tmpSecretId,
  55. SecretKey: credentials.tmpSecretKey,
  56. Method: options.Method,
  57. Pathname: options.Pathname,
  58. })
  59. });
  60. } else {
  61. console.error(xhr.responseText);
  62. callback('获取签名出错');
  63. }
  64. } else {
  65. callback('获取签名出错');
  66. }
  67. }
  68. };
  69. xhr.send();
  70. };
  71. // 上传文件
  72. var uploadFile = function (file, callback) {
  73. var Key = 'dir/' + file.name; // 这里指定上传目录和文件名
  74. getAuthorization({Method: 'POST', Pathname: '/'}, function (err, info) {
  75. var fd = new FormData();
  76. fd.append('key', Key);
  77. fd.append('signature', info.Authorization);
  78. fd.append('Content-Type', '');
  79. info.XCosSecurityToken && fd.append('x-cos-security-token', info.XCosSecurityToken);
  80. fd.append('file', file);
  81. var url = prefix;
  82. var xhr = new XMLHttpRequest();
  83. xhr.open('POST', url, true);
  84. xhr.upload.onprogress = function (e) {
  85. console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
  86. };
  87. xhr.onload = function () {
  88. if (Math.floor(xhr.status / 100) === 2) {
  89. var ETag = xhr.getResponseHeader('etag');
  90. callback(null, {url: prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/'), ETag: ETag});
  91. } else {
  92. callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
  93. }
  94. };
  95. xhr.onerror = function () {
  96. callback('文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则');
  97. };
  98. xhr.send(fd);
  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>