sts-form.html 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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>Form 表单简单上传(兼容 IE8)</h1>
  10. <div>最低兼容到 IE6 上传,不支持 onprogress</div>
  11. <form id="form" target="submitTarget" action="" method="post" enctype="multipart/form-data" accept="*/*">
  12. <input id="name" name="name" type="hidden" value="">
  13. <input name="success_action_status" type="hidden" value="200">
  14. <input id="success_action_redirect" name="success_action_redirect" type="hidden" value="">
  15. <input id="key" name="key" type="hidden" value="">
  16. <input id="Signature" name="Signature" type="hidden" value="">
  17. <input name="Content-Type" type="hidden" value="">
  18. <input id="x-cos-security-token" name="x-cos-security-token" type="hidden" value="">
  19. <!-- file 字段放在表单最后,避免文件内容过长影响签名判断和鉴权 -->
  20. <input id="fileSelector" name="file" type="file">
  21. <input id="submitBtn" type="button" value="提交">
  22. </form>
  23. <iframe id="submitTarget" name="submitTarget" style="display:none;" frameborder="0"></iframe>
  24. <div id="msg"></div>
  25. <script src="common/cos-auth.min.js"></script>
  26. <script>
  27. (function () {
  28. // 请求用到的参数
  29. var Bucket = 'test-1250000000';
  30. var Region = 'ap-guangzhou';
  31. var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
  32. var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';
  33. var form = document.getElementById('form');
  34. form.action = prefix;
  35. // 对更多字符编码的 url encode 格式
  36. var camSafeUrlEncode = function (str) {
  37. return encodeURIComponent(str)
  38. .replace(/!/g, '%21')
  39. .replace(/'/g, '%27')
  40. .replace(/\(/g, '%28')
  41. .replace(/\)/g, '%29')
  42. .replace(/\*/g, '%2A');
  43. };
  44. // 计算签名
  45. var getAuthorization = function (options, callback) {
  46. // var url = 'http://127.0.0.1:3000/sts';
  47. var url = '../server/sts.php';
  48. var xhr = new XMLHttpRequest();
  49. xhr.open('GET', url, true);
  50. xhr.onreadystatechange = function (e) {
  51. if (xhr.readyState === 4) {
  52. if (xhr.status === 200) {
  53. var credentials;
  54. try {
  55. credentials = (new Function('return ' + xhr.responseText))().credentials;
  56. } catch (e) {}
  57. if (credentials) {
  58. callback(null, {
  59. SecurityToken: credentials.sessionToken,
  60. Authorization: CosAuth({
  61. SecretId: credentials.tmpSecretId,
  62. SecretKey: credentials.tmpSecretKey,
  63. Method: options.Method,
  64. Pathname: options.Pathname,
  65. })
  66. });
  67. } else {
  68. console.error(xhr.responseText);
  69. callback('获取签名出错');
  70. }
  71. } else {
  72. callback('获取签名出错');
  73. }
  74. }
  75. };
  76. xhr.send();
  77. };
  78. // 监听上传完成
  79. var Key;
  80. var submitTarget = document.getElementById('submitTarget');
  81. var showMessage = function (err, data) {
  82. console.log(err || data);
  83. document.getElementById('msg').innerText = err ? err : ('上传成功,ETag=' + data.ETag);
  84. };
  85. submitTarget.onload = function () {
  86. var search;
  87. try {
  88. search = submitTarget.contentWindow.location.search.substr(1);
  89. } catch (e) {
  90. showMessage('文件 ' + Key + ' 上传失败');
  91. }
  92. if (search) {
  93. var items = search.split('&');
  94. var i, arr, data = {};
  95. for (i = 0; i < items.length; i++) {
  96. arr = items[i].split('=');
  97. data[arr[0]] = decodeURIComponent(arr[1] || '');
  98. }
  99. showMessage(null, {url: prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/'), ETag: data.etag});
  100. } else {
  101. }
  102. };
  103. // 发起上传
  104. document.getElementById('submitBtn').onclick = function (e) {
  105. var filePath = document.getElementById('fileSelector').value;
  106. if (!filePath) {
  107. document.getElementById('msg').innerText = '未选择上传文件';
  108. return;
  109. }
  110. Key = 'dir/' + filePath.match(/[\\\/]?([^\\\/]+)$/)[1]; // 这里指定上传目录和文件名
  111. getAuthorization({Method: 'POST', Pathname: '/'}, function (err, AuthData) {
  112. // 在当前目录下放一个空的 empty.html 以便让接口上传完成跳转回来
  113. document.getElementById('success_action_redirect').value = location.href.substr(0, location.href.lastIndexOf('/') + 1) + 'empty.html';
  114. document.getElementById('key').value = Key;
  115. document.getElementById('signature').value = AuthData.Authorization;
  116. document.getElementById('x-cos-security-token').value = AuthData.SecurityToken || '';
  117. form.submit();
  118. });
  119. };
  120. })();
  121. </script>
  122. </body>
  123. </html>