policy-post.html 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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>PostObject 上传(Policy 保护,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 getPostPolicyCredentials = function (opt, callback) {
  39. var url = 'http://127.0.0.1:3000/post-policy?key=' + encodeURIComponent(opt.Key);
  40. var xhr = new XMLHttpRequest();
  41. xhr.open('GET', url, true);
  42. xhr.onreadystatechange = function (e) {
  43. if (xhr.readyState === 4) {
  44. if (xhr.status === 200) {
  45. var credentials;
  46. try {
  47. credentials = (new Function('return ' + xhr.responseText))();
  48. } catch (e) {}
  49. if (credentials) {
  50. callback(null, credentials);
  51. } else {
  52. console.error(xhr.responseText);
  53. callback('获取签名出错');
  54. }
  55. } else {
  56. callback('获取签名出错');
  57. }
  58. }
  59. };
  60. xhr.send();
  61. };
  62. // 上传文件
  63. var uploadFile = function (file, callback) {
  64. var Key = 'dir/' + file.name; // 这里指定上传目录和文件名
  65. getPostPolicyCredentials({
  66. Bucket: Bucket,
  67. Key: Key,
  68. ACL: 'default'
  69. }, function (err, credentials) {
  70. var fd = new FormData();
  71. // 在当前目录下放一个空的 empty.html 以便让接口上传完成跳转回来
  72. fd.append('key', Key);
  73. // // 使用普通签名格式
  74. // fd.append('Signature', credentials.Authorization);
  75. // fd.append('x-cos-security-token', credentials.SecurityToken || '');
  76. // 使用 policy 签名保护格式
  77. credentials.securityToken && fd.append('x-cos-security-token', credentials.securityToken);
  78. fd.append('q-sign-algorithm', credentials.qSignAlgorithm);
  79. fd.append('q-ak', credentials.qAk);
  80. fd.append('q-key-time', credentials.qKeyTime);
  81. fd.append('q-signature', credentials.qSignature);
  82. fd.append('policy', credentials.policy);
  83. // 文件内容,file 字段放在表单最后,避免文件内容过长影响签名判断和鉴权
  84. fd.append('file', file);
  85. // xhr
  86. var url = prefix;
  87. var xhr = new XMLHttpRequest();
  88. xhr.open('POST', url, true);
  89. xhr.upload.onprogress = function (e) {
  90. console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
  91. };
  92. xhr.onload = function () {
  93. if (Math.floor(xhr.status / 100) === 2) {
  94. var ETag = xhr.getResponseHeader('etag');
  95. callback(null, {url: prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/'), ETag: ETag});
  96. } else {
  97. callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
  98. }
  99. };
  100. xhr.onerror = function () {
  101. callback('文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则');
  102. };
  103. xhr.send(fd);
  104. });
  105. };
  106. // 监听表单提交
  107. document.getElementById('submitBtn').onclick = function (e) {
  108. var file = document.getElementById('fileSelector').files[0];
  109. if (!file) {
  110. document.getElementById('msg').innerText = '未选择上传文件';
  111. return;
  112. }
  113. file && uploadFile(file, function (err, data) {
  114. console.log(err || data);
  115. document.getElementById('msg').innerText = err ? err : ('上传成功,ETag=' + data.ETag);
  116. });
  117. };
  118. })();
  119. </script>
  120. </body>
  121. </html>