mime-limit.html 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>上传限制 Content-Type</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>上传限制 Content-Type</h1>
  17. <input id="fileSelector" type="file">
  18. <input id="submitBtn" type="submit">
  19. <div id="msg"></div>
  20. <script src="../dist/cos-js-sdk-v5.js"></script>
  21. <script>
  22. (function () {
  23. // 计算签名
  24. var getUploadSign = function (options, callback) {
  25. var url = '/uploadSign?filename=' + encodeURIComponent(options.filename) + '&_=' + Date.now();
  26. var xhr = new XMLHttpRequest();
  27. xhr.open('POST', url, true);
  28. xhr.onload = function (e) {
  29. var token;
  30. try {
  31. token = (new Function('return ' + xhr.responseText))();
  32. } catch (e) {}
  33. if (token) {
  34. callback(null, token);
  35. } else {
  36. console.error(xhr.responseText);
  37. callback('获取签名出错');
  38. }
  39. };
  40. xhr.onerror = function (e) {
  41. callback('获取签名出错');
  42. };
  43. xhr.send();
  44. };
  45. // 上传文件
  46. var uploadFile = function (file, callback) {
  47. getUploadSign({ filename: file.name }, function (err, info) {
  48. if (err) {
  49. alert(err);
  50. return;
  51. }
  52. var signMap = info.signMap;
  53. var mimeLimit = info.mimeLimit;
  54. var allowActions = ['ListMultipartUploads', 'ListParts', 'InitiateMultipartUpload', 'UploadPart', 'CompleteMultipartUpload', 'PutObject'];
  55. var cos = new COS({
  56. getAuthorization: function (opt, cb) {
  57. var action = opt.Scope[0].action.split(':')[1];
  58. if (allowActions.indexOf(action) === -1) return console.error('action not allow');
  59. var auth = signMap[action];
  60. cb({ Authorization: auth });
  61. },
  62. });
  63. cos.uploadFile({
  64. Bucket: info.bucket,
  65. Region: info.region,
  66. Key: info.key,
  67. Body: file,
  68. SliceSize: 1024 * 1024 * 8,
  69. ChunkSize: 1024 * 1024 * 8,
  70. Headers: {
  71. 'x-cos-mime-limit': mimeLimit,
  72. },
  73. }, function (err, data) {
  74. callback(err, data);
  75. });
  76. });
  77. };
  78. // 监听表单提交
  79. document.getElementById('submitBtn').onclick = function (e) {
  80. var file = document.getElementById('fileSelector').files[0];
  81. if (!file) {
  82. document.getElementById('msg').innerText = '未选择上传文件';
  83. return;
  84. }
  85. file && uploadFile(file, function (err, data) {
  86. console.log(err || data);
  87. document.getElementById('msg').innerText = err ? '上传失败:' + err.code + '(' + err.message + ')' : ('上传成功,ETag=' + data.ETag);
  88. });
  89. };
  90. })();
  91. </script>
  92. </body>
  93. </html>