policy-form.html 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Form 表单简单上传</title>
  6. <style>h1, h2 {font-weight: normal;}#msg {margin-top:10px;}</style>
  7. </head>
  8. <body>
  9. <h1>PostObject 上传(Policy 保护,Form 表单上传)</h1>
  10. <div>最低兼容到 IE6 上传,使用 policy 签名保护,不支持 onprogress</div>
  11. <form id="form" target="submitTarget" action="" method="post" enctype="multipart/form-data" accept="*/*">
  12. <!-- file 字段放在表单最后,避免文件内容过长影响签名判断和鉴权 -->
  13. <input id="fileSelector" name="file" type="file">
  14. <input id="submitBtn" type="button" value="提交">
  15. </form>
  16. <iframe id="submitTarget" name="submitTarget" style="display:none;" frameborder="0"></iframe>
  17. <div id="msg"></div>
  18. <script src="common/cos-auth.min.js"></script>
  19. <script>
  20. (function () {
  21. // 请求用到的参数
  22. var Bucket = 'test-1250000000';
  23. var Region = 'ap-guangzhou';
  24. var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
  25. var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';
  26. var fileSelector = document.getElementById('fileSelector');
  27. var form = document.getElementById('form');
  28. form.action = prefix;
  29. // 对更多字符编码的 url encode 格式
  30. var camSafeUrlEncode = function (str) {
  31. return encodeURIComponent(str)
  32. .replace(/!/g, '%21')
  33. .replace(/'/g, '%27')
  34. .replace(/\(/g, '%28')
  35. .replace(/\)/g, '%29')
  36. .replace(/\*/g, '%2A');
  37. };
  38. // 获取权限策略
  39. var getPostPolicyCredentials = function (opt, callback) {
  40. var url = 'http://127.0.0.1:3000/post-policy?key=' + encodeURIComponent(opt.Key);
  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))();
  49. } catch (e) {}
  50. if (credentials) {
  51. callback(null, credentials);
  52. } else {
  53. console.error(xhr.responseText);
  54. callback('获取签名出错');
  55. }
  56. } else {
  57. callback('获取签名出错');
  58. }
  59. }
  60. };
  61. xhr.send();
  62. };
  63. // 监听上传完成
  64. var Key;
  65. var submitTarget = document.getElementById('submitTarget');
  66. var showMessage = function (err, data) {
  67. console.log(err || data);
  68. document.getElementById('msg').innerText = err ? err : ('上传成功,ETag=' + data.ETag);
  69. };
  70. submitTarget.onload = function () {
  71. var search;
  72. try {
  73. search = submitTarget.contentWindow.location.search.substr(1);
  74. } catch (e) {
  75. showMessage('文件 ' + Key + ' 上传失败');
  76. }
  77. if (search) {
  78. var items = search.split('&');
  79. var i, arr, data = {};
  80. for (i = 0; i < items.length; i++) {
  81. arr = items[i].split('=');
  82. data[arr[0]] = decodeURIComponent(arr[1] || '');
  83. }
  84. showMessage(null, {url: prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/'), ETag: data.etag});
  85. } else {
  86. }
  87. };
  88. var setFormField = function (key, value) {
  89. var el = document.getElementById(key);
  90. if (!el) {
  91. el = document.createElement('input');
  92. el.hidden = true;
  93. el.id = key;
  94. el.name = key;
  95. form.insertBefore(el, fileSelector);
  96. }
  97. el.setAttribute('value', value); // 需要保证 file 在表单最后
  98. el.value = value;
  99. };
  100. // 发起上传
  101. document.getElementById('submitBtn').onclick = function (e) {
  102. var filePath = document.getElementById('fileSelector').value;
  103. if (!filePath) {
  104. document.getElementById('msg').innerText = '未选择上传文件';
  105. return;
  106. }
  107. Key = 'dir/' + filePath.match(/[\\\/]?([^\\\/]+)$/)[1]; // 这里指定上传目录和文件名
  108. // 获取签名保护字段
  109. getPostPolicyCredentials({
  110. Key: Key,
  111. }, function (err, credentials) {
  112. // 在当前目录下放一个空的 empty.html 以便让接口上传完成跳转回来
  113. setFormField('success_action_redirect', location.href.substr(0, location.href.lastIndexOf('/') + 1) + 'empty.html');
  114. setFormField('key', Key);
  115. // 使用 policy 签名保护格式
  116. credentials.securityToken && setFormField('x-cos-security-token', credentials.securityToken);
  117. setFormField('q-sign-algorithm', credentials.qSignAlgorithm);
  118. setFormField('q-ak', credentials.qAk);
  119. setFormField('q-key-time', credentials.qKeyTime);
  120. setFormField('q-signature', credentials.qSignature);
  121. setFormField('policy', credentials.policy);
  122. // 提交表单
  123. form.submit();
  124. });
  125. };
  126. })();
  127. </script>
  128. </body>
  129. </html>