demo.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. // @ts-check
  2. // config 替换成自己的存储桶和账号信息
  3. var config = {
  4. Bucket: 'test-1250000000',
  5. Region: 'ap-guangzhou',
  6. Uin: '10001',
  7. };
  8. var util = {
  9. createFile: function (options) {
  10. var buffer = new ArrayBuffer(options.size || 0);
  11. var arr = new Uint8Array(buffer);
  12. [].forEach.call(arr, function (char, i) {
  13. arr[i] = 0;
  14. });
  15. var opt = {};
  16. options.type && (opt.type = options.type);
  17. var blob = new Blob([buffer], options);
  18. return blob;
  19. },
  20. selectLocalFile: function (onChange) {
  21. var id = 'file_selector';
  22. var input = document.createElement('input');
  23. input.style = 'width:0;height:0;border:0;margin:0;padding:0;';
  24. input.type = 'file';
  25. input.id = id;
  26. input.onchange = function (e) {
  27. var files = this.files;
  28. if (!files.length) return;
  29. onChange && onChange(files);
  30. document.body.removeChild(input);
  31. };
  32. document.body.appendChild(input);
  33. input.click();
  34. },
  35. };
  36. // 对更多字符编码的 url encode 格式
  37. var camSafeUrlEncode = function (str) {
  38. return encodeURIComponent(str)
  39. .replace(/!/g, '%21')
  40. .replace(/'/g, '%27')
  41. .replace(/\(/g, '%28')
  42. .replace(/\)/g, '%29')
  43. .replace(/\*/g, '%2A');
  44. };
  45. var getAuthorization = function (options, callback) {
  46. // 格式一、(推荐)后端通过获取临时密钥给到前端,前端计算签名
  47. // 服务端 JS 和 PHP 例子:https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
  48. // 服务端其他语言参考 COS STS SDK :https://github.com/tencentyun/qcloud-cos-sts-sdk
  49. // var url = '../server/sts.php'; // 如果起的是 php server 用这个
  50. var url = '/sts'; // 如果是 npm run sts.js 起的 nodejs server,使用这个
  51. var xhr = new XMLHttpRequest();
  52. xhr.open('GET', url, true);
  53. xhr.onload = function (e) {
  54. try {
  55. var data = JSON.parse(e.target.responseText);
  56. var credentials = data.credentials;
  57. } catch (e) {
  58. }
  59. if (!data || !credentials) {
  60. return logger.error('credentials invalid:\n' + JSON.stringify(data, null, 2))
  61. };
  62. var authorization = COS.getAuthorization({
  63. SecretId: credentials.tmpSecretId, // 可传固定密钥或者临时密钥
  64. SecretKey: credentials.tmpSecretKey, // 可传固定密钥或者临时密钥
  65. Method: options.Method,
  66. Pathname: options.Pathname,
  67. Query: options.Query,
  68. Headers: options.Headers,
  69. Expires: 900,
  70. });
  71. callback({
  72. Authorization: authorization,
  73. XCosSecurityToken: credentials.sessionToken,
  74. });
  75. };
  76. xhr.send();
  77. // // 格式二、(推荐)【细粒度控制权限】后端通过获取临时密钥给到前端,前端只有相同请求才重复使用临时密钥,后端可以通过 Scope 细粒度控制权限
  78. // // 服务端例子:https://github.com/tencentyun/qcloud-cos-sts-sdk/edit/master/scope.md
  79. // // var url = '../server/sts.php'; // 如果起的是 php server 用这个
  80. // var url = '/sts-scope'; // 如果是 npm run sts.js 起的 nodejs server,使用这个
  81. // var xhr = new XMLHttpRequest();
  82. // xhr.open('POST', url, true);
  83. // xhr.setRequestHeader('Content-Type', 'application/json');
  84. // xhr.onload = function (e) {
  85. // try {
  86. // var data = JSON.parse(e.target.responseText);
  87. // var credentials = data.credentials;
  88. // } catch (e) {
  89. // }
  90. // if (!data || !credentials) {
  91. // return logger.error('credentials invalid:\n' + JSON.stringify(data, null, 2))
  92. // };
  93. // callback({
  94. // TmpSecretId: credentials.tmpSecretId,
  95. // TmpSecretKey: credentials.tmpSecretKey,
  96. // SecurityToken: credentials.sessionToken,
  97. // StartTime: data.startTime, // 时间戳,单位秒,如:1580000000,建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
  98. // ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000000
  99. // ScopeLimit: true, // 细粒度控制权限需要设为 true,会限制密钥只在相同请求时重复使用
  100. // });
  101. // };
  102. // xhr.send(JSON.stringify(options.Scope));
  103. // // 格式三、(不推荐,分片上传权限不好控制)前端每次请求前都需要通过 getAuthorization 获取签名,后端使用固定密钥或临时密钥计算签名返回给前端
  104. // // 服务端获取签名,请参考对应语言的 COS SDK:https://cloud.tencent.com/document/product/436/6474
  105. // // 注意:这种有安全风险,后端需要通过 method、pathname 严格控制好权限,比如不允许 put / 等
  106. // var method = (options.Method || 'get').toLowerCase();
  107. // var query = options.Query || {};
  108. // var headers = options.Headers || {};
  109. // var pathname = options.Pathname || '/';
  110. // // var url = 'http://127.0.0.1:3000/auth';
  111. // var url = '../server/auth.php';
  112. // var xhr = new XMLHttpRequest();
  113. // var data = {
  114. // method: method,
  115. // pathname: pathname,
  116. // query: query,
  117. // headers: headers,
  118. // };
  119. // xhr.open('POST', url, true);
  120. // xhr.setRequestHeader('content-type', 'application/json');
  121. // xhr.onload = function (e) {
  122. // try {
  123. // var data = JSON.parse(e.target.responseText);
  124. // } catch (e) {
  125. // }
  126. // if (!data || !data.authorization) return console.error('authorization invalid');
  127. // callback({
  128. // Authorization: data.authorization,
  129. // // SecurityToken: data.sessionToken, // 如果使用临时密钥,需要把 sessionToken 传给 SecurityToken
  130. // });
  131. // };
  132. // xhr.send(JSON.stringify(data));
  133. // // 格式四、(不推荐,适用于前端调试,避免泄露密钥)前端使用固定密钥计算签名
  134. // var authorization = COS.getAuthorization({
  135. // SecretId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 可传固定密钥或者临时密钥
  136. // SecretKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 可传固定密钥或者临时密钥
  137. // Method: options.Method,
  138. // Pathname: options.Pathname,
  139. // Query: options.Query,
  140. // Headers: options.Headers,
  141. // Expires: 900,
  142. // });
  143. // callback({
  144. // Authorization: authorization,
  145. // // SecurityToken: credentials.sessionToken, // 如果使用临时密钥,需要传 SecurityToken
  146. // });
  147. };
  148. var cos = new COS({
  149. getAuthorization: getAuthorization,
  150. UploadCheckContentMd5: true,
  151. });
  152. var TaskId;
  153. var pre = document.querySelector('.result');
  154. var showLogText = function (text, color) {
  155. if (typeof text === 'object') {
  156. try {
  157. text = JSON.stringify(text);
  158. } catch (e) {
  159. }
  160. }
  161. var div = document.createElement('div');
  162. div.innerText = text;
  163. color && (div.style.color = color);
  164. pre.appendChild(div);
  165. pre.style.display = 'block';
  166. pre.scrollTop = pre.scrollHeight;
  167. };
  168. var logger = {
  169. log: function (text) {
  170. console.log.apply(console, arguments);
  171. var args = [].map.call(arguments, function (v) {
  172. return typeof v === 'object' ? JSON.stringify(v, null, 2) : v;
  173. });
  174. var logStr = args.join(' ');
  175. if(logStr.length > 1000000) {
  176. logStr = logStr.slice(0, 1000000) + '...content is too long, the first 1000000 characters are intercepted';
  177. }
  178. showLogText(logStr);
  179. },
  180. error: function (text) {
  181. console.error(text);
  182. showLogText(text, 'red');
  183. },
  184. };
  185. function getObjectUrl() {
  186. var url = cos.getObjectUrl({
  187. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  188. Region: config.Region,
  189. Key: '1mb.zip',
  190. Expires: 60,
  191. Sign: true,
  192. }, function (err, data) {
  193. logger.log('getObjectUrl:', err || data && data.Url);
  194. });
  195. logger.log('getObjectUrl:', url);
  196. }
  197. function getAuth() {
  198. var key = '1.png';
  199. // 这里不推荐自己拼接,推荐使用 getObjectUrl 获取 url
  200. getAuthorization({
  201. Method: 'get',
  202. Key: key
  203. }, function (AuthData) {
  204. if (typeof AuthData === 'string') {
  205. AuthData = {Authorization: AuthData};
  206. }
  207. var url = 'http://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com' + '/' +
  208. camSafeUrlEncode(key).replace(/%2F/g, '/') +
  209. '?' + AuthData +
  210. (AuthData.SecurityToken ? '&' + AuthData.SecurityToken : '');
  211. logger.log('getAuth:', url);
  212. });
  213. }
  214. // getService、putBucket 接口会跨域,不支持浏览器使用,只在场景下可调用,比如改了 ServiceDomain 到代理地址
  215. function getService() {
  216. cos.getService(function (err, data) {
  217. logger.log('getService:', err || data);
  218. });
  219. }
  220. // getService、putBucket 接口会跨域,不支持浏览器使用,只在场景下可调用,比如改了 ServiceDomain 到代理地址
  221. function putBucket() {
  222. cos.putBucket({
  223. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  224. Region: config.Region,
  225. // Prefix: 'dir/'
  226. // Delimiter: '/'
  227. }, function (err, data) {
  228. logger.log('putBucket:', err || data);
  229. });
  230. }
  231. function getBucket() {
  232. cos.getBucket({
  233. // Bucket: config.Bucket, // Bucket 格式:test-1250000000
  234. // Region: config.Region,
  235. // Prefix: 'dir/'
  236. // Delimiter: '/'
  237. }, function (err, data) {
  238. logger.log('getBucket:', err || data);
  239. });
  240. }
  241. function headBucket() {
  242. cos.headBucket({
  243. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  244. Region: config.Region
  245. }, function (err, data) {
  246. logger.log('headBucket:', err || data);
  247. });
  248. }
  249. function deleteBucket() {
  250. cos.deleteBucket({
  251. Bucket: 'testnew-' + config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1),
  252. Region: 'ap-guangzhou'
  253. }, function (err, data) {
  254. logger.log('deleteBucket:', err || data);
  255. });
  256. }
  257. function putBucketAcl() {
  258. cos.putBucketAcl({
  259. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  260. Region: config.Region,
  261. // GrantFullControl: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  262. // GrantWrite: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  263. // GrantRead: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  264. // GrantReadAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  265. // GrantWriteAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  266. // ACL: 'public-read-write',
  267. // ACL: 'public-read',
  268. ACL: 'private',
  269. // AccessControlPolicy: {
  270. // "Owner": { // AccessControlPolicy 里必须有 owner
  271. // "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 Bucket 所属用户的 QQ 号
  272. // },
  273. // "Grants": [{
  274. // "Grantee": {
  275. // "URI": "http://cam.qcloud.com/groups/global/AllUsers", // 允许匿名用户组访问
  276. // },
  277. // "Permission": "READ"
  278. // }, {
  279. // "Grantee": {
  280. // "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  281. // },
  282. // "Permission": "WRITE"
  283. // }, {
  284. // "Grantee": {
  285. // "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  286. // },
  287. // "Permission": "READ_ACP"
  288. // }, {
  289. // "Grantee": {
  290. // "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  291. // },
  292. // "Permission": "WRITE_ACP"
  293. // }]
  294. // }
  295. }, function (err, data) {
  296. logger.log('putBucketAcl:', err || data);
  297. });
  298. }
  299. function getBucketAcl() {
  300. cos.getBucketAcl({
  301. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  302. Region: config.Region
  303. }, function (err, data) {
  304. logger.log('getBucketAcl:', err || data);
  305. });
  306. }
  307. function putBucketCors() {
  308. cos.putBucketCors({
  309. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  310. Region: config.Region,
  311. CORSRules: [{
  312. "AllowedOrigin": ["*"],
  313. "AllowedMethod": ["GET", "POST", "PUT", "DELETE", "HEAD"],
  314. "AllowedHeader": ["*"],
  315. "ExposeHeader": ["ETag", "Date", "Content-Length", "x-cos-acl", "x-cos-version-id", "x-cos-request-id", "x-cos-delete-marker", "x-cos-server-side-encryption"],
  316. "MaxAgeSeconds": "5"
  317. }]
  318. }, function (err, data) {
  319. logger.log('putBucketCors:', err || data);
  320. });
  321. }
  322. function getBucketCors() {
  323. cos.getBucketCors({
  324. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  325. Region: config.Region
  326. }, function (err, data) {
  327. logger.log('getBucketCors:', err || data);
  328. });
  329. }
  330. function deleteBucketCors() {
  331. cos.deleteBucketCors({
  332. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  333. Region: config.Region
  334. }, function (err, data) {
  335. logger.log('deleteBucketCors:', err || data);
  336. });
  337. }
  338. function putBucketTagging() {
  339. cos.putBucketTagging({
  340. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  341. Region: config.Region,
  342. Tagging: {
  343. "Tags": [
  344. {"Key": "k1", "Value": "v1"},
  345. {"Key": "k2", "Value": "v2"}
  346. ]
  347. }
  348. }, function (err, data) {
  349. logger.log('putBucketTagging:', err || data);
  350. });
  351. }
  352. function getBucketTagging() {
  353. cos.getBucketTagging({
  354. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  355. Region: config.Region
  356. }, function (err, data) {
  357. logger.log('getBucketTagging:', err || data);
  358. });
  359. }
  360. function deleteBucketTagging() {
  361. cos.deleteBucketTagging({
  362. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  363. Region: config.Region
  364. }, function (err, data) {
  365. logger.log('deleteBucketTagging:', err || data);
  366. });
  367. }
  368. function putBucketPolicy() {
  369. var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
  370. cos.putBucketPolicy({
  371. Policy: {
  372. "version": "2.0",
  373. "statement": [{
  374. "effect": "allow",
  375. "principal": {"qcs": ["qcs::cam::uin/10001:uin/10001"]}, // 这里的 10001 是 QQ 号
  376. "action": [
  377. // 这里可以从临时密钥的权限上控制前端允许的操作
  378. // 'name/cos:*', // 这样写可以包含下面所有权限
  379. // // 列出所有允许的操作
  380. // // ACL 读写
  381. // 'name/cos:GetBucketACL',
  382. // 'name/cos:PutBucketACL',
  383. // 'name/cos:GetObjectACL',
  384. // 'name/cos:PutObjectACL',
  385. // // 简单 Bucket 操作
  386. // 'name/cos:PutBucket',
  387. // 'name/cos:HeadBucket',
  388. // 'name/cos:GetBucket',
  389. // 'name/cos:DeleteBucket',
  390. // 'name/cos:GetBucketLocation',
  391. // // Versioning
  392. // 'name/cos:PutBucketVersioning',
  393. // 'name/cos:GetBucketVersioning',
  394. // // CORS
  395. // 'name/cos:PutBucketCORS',
  396. // 'name/cos:GetBucketCORS',
  397. // 'name/cos:DeleteBucketCORS',
  398. // // Lifecycle
  399. // 'name/cos:PutBucketLifecycle',
  400. // 'name/cos:GetBucketLifecycle',
  401. // 'name/cos:DeleteBucketLifecycle',
  402. // // Replication
  403. // 'name/cos:PutBucketReplication',
  404. // 'name/cos:GetBucketReplication',
  405. // 'name/cos:DeleteBucketReplication',
  406. // // 删除文件
  407. // 'name/cos:DeleteMultipleObject',
  408. // 'name/cos:DeleteObject',
  409. // 简单文件操作
  410. 'name/cos:PutObject',
  411. 'name/cos:AppendObject',
  412. 'name/cos:GetObject',
  413. 'name/cos:HeadObject',
  414. 'name/cos:OptionsObject',
  415. 'name/cos:PutObjectCopy',
  416. 'name/cos:PostObjectRestore',
  417. // 分片上传操作
  418. 'name/cos:InitiateMultipartUpload',
  419. 'name/cos:ListMultipartUploads',
  420. 'name/cos:ListParts',
  421. 'name/cos:UploadPart',
  422. 'name/cos:CompleteMultipartUpload',
  423. 'name/cos:AbortMultipartUpload',
  424. ],
  425. // "resource": ["qcs::cos:ap-guangzhou:uid/1250000000:test-1250000000/*"] // 1250000000 是 appid
  426. "resource": ["qcs::cos:" + config.Region + ":uid/" + AppId + ":" + config.Bucket + "/*"] // 1250000000 是 appid
  427. }]
  428. },
  429. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  430. Region: config.Region
  431. }, function (err, data) {
  432. logger.log('putBucketPolicy:', err || data);
  433. });
  434. }
  435. function getBucketPolicy() {
  436. cos.getBucketPolicy({
  437. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  438. Region: config.Region
  439. }, function (err, data) {
  440. logger.log('getBucketPolicy:', err || data);
  441. });
  442. }
  443. function deleteBucketPolicy() {
  444. cos.deleteBucketPolicy({
  445. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  446. Region: config.Region
  447. }, function (err, data) {
  448. logger.log('deleteBucketPolicy:', err || data);
  449. });
  450. }
  451. function getBucketLocation() {
  452. cos.getBucketLocation({
  453. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  454. Region: config.Region
  455. }, function (err, data) {
  456. logger.log('getBucketLocation:', err || data);
  457. });
  458. }
  459. function putBucketLifecycle() {
  460. cos.putBucketLifecycle({
  461. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  462. Region: config.Region,
  463. LifecycleConfiguration: {
  464. Rules: [{
  465. "ID": "1",
  466. "Status": "Enabled",
  467. "Filter": {},
  468. "Transition": {
  469. "Days": "30",
  470. "StorageClass": "STANDARD_IA"
  471. }
  472. }, {
  473. "ID": "2",
  474. "Status": "Enabled",
  475. "Filter": {
  476. "Prefix": "dir/"
  477. },
  478. "Transition": {
  479. "Days": "90",
  480. "StorageClass": "ARCHIVE"
  481. }
  482. }, {
  483. "ID": "3",
  484. "Status": "Enabled",
  485. "Filter": {},
  486. "Expiration": {
  487. "Days": "180"
  488. }
  489. }, {
  490. "ID": "4",
  491. "Status": "Enabled",
  492. "Filter": {},
  493. "AbortIncompleteMultipartUpload": {
  494. "DaysAfterInitiation": "30"
  495. }
  496. }],
  497. }
  498. }, function (err, data) {
  499. logger.log('putBucketLifecycle:', err || data);
  500. });
  501. }
  502. function getBucketLifecycle() {
  503. cos.getBucketLifecycle({
  504. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  505. Region: config.Region
  506. }, function (err, data) {
  507. logger.log('getBucketLifecycle:', err || data);
  508. });
  509. }
  510. function deleteBucketLifecycle() {
  511. cos.deleteBucketLifecycle({
  512. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  513. Region: config.Region
  514. }, function (err, data) {
  515. logger.log('deleteBucketLifecycle:', err || data);
  516. });
  517. }
  518. function putBucketVersioning() {
  519. cos.putBucketVersioning({
  520. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  521. Region: config.Region,
  522. VersioningConfiguration: {
  523. Status: "Enabled"
  524. }
  525. }, function (err, data) {
  526. logger.log('putBucketVersioning:', err || data);
  527. });
  528. }
  529. function getBucketVersioning() {
  530. cos.getBucketVersioning({
  531. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  532. Region: config.Region
  533. }, function (err, data) {
  534. logger.log('getBucketVersioning:', err || data);
  535. });
  536. }
  537. function listObjectVersions() {
  538. cos.listObjectVersions({
  539. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  540. Region: config.Region,
  541. // Prefix: "",
  542. // Delimiter: '/'
  543. }, function (err, data) {
  544. logger.log('listObjectVersions:', err || JSON.stringify(data, null, ' '));
  545. });
  546. }
  547. function putBucketReplication() {
  548. var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
  549. cos.putBucketReplication({
  550. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  551. Region: config.Region,
  552. ReplicationConfiguration: {
  553. Role: "qcs::cam::uin/10001:uin/10001",
  554. Rules: [{
  555. ID: "1",
  556. Status: "Enabled",
  557. Prefix: "sync/",
  558. Destination: {
  559. Bucket: "qcs:id/0:cos:ap-chengdu:appid/" + AppId + ":backup",
  560. // StorageClass: "Standard",
  561. }
  562. }]
  563. }
  564. }, function (err, data) {
  565. logger.log('putBucketReplication:', err || data);
  566. });
  567. }
  568. function getBucketReplication() {
  569. cos.getBucketReplication({
  570. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  571. Region: config.Region
  572. }, function (err, data) {
  573. logger.log('getBucketReplication:', err || data);
  574. });
  575. }
  576. function deleteBucketReplication() {
  577. cos.deleteBucketReplication({
  578. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  579. Region: config.Region
  580. }, function (err, data) {
  581. logger.log('deleteBucketReplication:', err || data);
  582. });
  583. }
  584. function putBucketWebsite() {
  585. cos.putBucketWebsite({
  586. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  587. Region: config.Region,
  588. WebsiteConfiguration: {
  589. IndexDocument: {
  590. Suffix: "index.html" // 必选
  591. },
  592. RedirectAllRequestsTo: {
  593. Protocol: "https"
  594. },
  595. // ErrorDocument: {
  596. // Key: "error.html"
  597. // },
  598. // RoutingRules: [{
  599. // Condition: {
  600. // HttpErrorCodeReturnedEquals: "404"
  601. // },
  602. // Redirect: {
  603. // Protocol: "https",
  604. // ReplaceKeyWith: "404.html"
  605. // }
  606. // }, {
  607. // Condition: {
  608. // KeyPrefixEquals: "docs/"
  609. // },
  610. // Redirect: {
  611. // Protocol: "https",
  612. // ReplaceKeyPrefixWith: "documents/"
  613. // }
  614. // }, {
  615. // Condition: {
  616. // KeyPrefixEquals: "img/"
  617. // },
  618. // Redirect: {
  619. // Protocol: "https",
  620. // ReplaceKeyWith: "picture.jpg"
  621. // }
  622. // }]
  623. }
  624. }, function (err, data) {
  625. logger.log('putBucketWebsite:', err || data);
  626. });
  627. }
  628. function getBucketWebsite() {
  629. cos.getBucketWebsite({
  630. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  631. Region: config.Region
  632. },function(err, data){
  633. logger.log('getBucketWebsite:', err || data);
  634. });
  635. }
  636. function deleteBucketWebsite() {
  637. cos.deleteBucketWebsite({
  638. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  639. Region: config.Region
  640. },function(err, data){
  641. logger.log('deleteBucketWebsite:', err || data);
  642. });
  643. }
  644. function putBucketReferer() {
  645. cos.putBucketReferer({
  646. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  647. Region: config.Region,
  648. RefererConfiguration: {
  649. Status: 'Enabled',
  650. RefererType: 'White-List',
  651. DomainList: {
  652. Domains: [
  653. '*.qq.com',
  654. '*.qcloud.com',
  655. ]
  656. },
  657. EmptyReferConfiguration: 'Allow',
  658. }
  659. }, function (err, data) {
  660. logger.log('putBucketReferer:', err || data);
  661. });
  662. }
  663. function getBucketReferer() {
  664. cos.getBucketReferer({
  665. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  666. Region: config.Region
  667. },function(err, data){
  668. logger.log('getBucketReferer:', err || JSON.stringify(data, null, ' '));
  669. });
  670. }
  671. function putBucketDomain() {
  672. cos.putBucketDomain({
  673. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  674. Region: config.Region,
  675. DomainRule:[{
  676. Status: "DISABLED",
  677. Name: "www.testDomain1.com",
  678. Type: "REST"
  679. }, {
  680. Status: "DISABLED",
  681. Name: "www.testDomain2.com",
  682. Type: "WEBSITE"
  683. }]
  684. },function(err, data){
  685. logger.log('putBucketDomain:', err || data);
  686. });
  687. }
  688. function getBucketDomain() {
  689. cos.getBucketDomain({
  690. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  691. Region: config.Region
  692. },function(err, data){
  693. logger.log('getBucketDomain:', err || data);
  694. });
  695. }
  696. function deleteBucketDomain() {
  697. cos.deleteBucketDomain({
  698. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  699. Region: config.Region
  700. },function(err, data){
  701. logger.log('deleteBucketDomain:', err || data);
  702. });
  703. }
  704. function putBucketLogging() {
  705. var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
  706. cos.putBucketLogging({
  707. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  708. Region: config.Region,
  709. BucketLoggingStatus: {
  710. LoggingEnabled: {
  711. TargetBucket: 'bucket-logging-' + AppId,
  712. TargetPrefix: 'logging'
  713. }
  714. }
  715. }, function (err, data) {
  716. logger.log('putBucketLogging:', err || data);
  717. });
  718. }
  719. function getBucketLogging() {
  720. cos.getBucketLogging({
  721. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  722. Region: config.Region
  723. }, function (err, data) {
  724. logger.log('getBucketLogging:', err || data);
  725. });
  726. }
  727. function deleteBucketLogging() {
  728. cos.putBucketLogging({
  729. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  730. Region: config.Region,
  731. BucketLoggingStatus: {}
  732. }, function (err, data) {
  733. logger.log('deleteBucketLogging:', err || data);
  734. });
  735. }
  736. function putBucketInventory() {
  737. var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
  738. cos.putBucketInventory({
  739. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  740. Region: config.Region,
  741. Id: 'inventory_test',
  742. InventoryConfiguration: {
  743. Id: 'inventory_test',
  744. IsEnabled: 'true',
  745. Destination: {
  746. COSBucketDestination: {
  747. Format: 'CSV',
  748. AccountId: config.Uin,
  749. Bucket: 'qcs::cos:' + config.Region + '::' + config.Bucket,
  750. Prefix: 'inventory',
  751. Encryption: {
  752. SSECOS: ''
  753. }
  754. }
  755. },
  756. Schedule: {
  757. Frequency: 'Daily'
  758. },
  759. Filter: {
  760. Prefix: 'myPrefix'
  761. },
  762. IncludedObjectVersions: 'All',
  763. OptionalFields: [
  764. 'Size',
  765. 'LastModifiedDate',
  766. 'ETag',
  767. 'StorageClass',
  768. 'IsMultipartUploaded',
  769. 'ReplicationStatus'
  770. ]
  771. }
  772. }, function (err, data) {
  773. logger.log('putBucketInventory:', err || data);
  774. });
  775. }
  776. function getBucketInventory() {
  777. cos.getBucketInventory({
  778. Bucket: config.Bucket,
  779. Region: config.Region,
  780. Id: 'inventory_test'
  781. }, function(err, data) {
  782. logger.log('getBucketInventory:', err || JSON.stringify(data));
  783. });
  784. }
  785. function deleteBucketInventory() {
  786. cos.deleteBucketInventory({
  787. Bucket: config.Bucket,
  788. Region: config.Region,
  789. Id: 'inventory_test'
  790. }, function(err, data) {
  791. logger.log('deleteBucketInventory:', err || JSON.stringify(data));
  792. });
  793. }
  794. function listBucketInventory() {
  795. cos.listBucketInventory({
  796. Bucket: config.Bucket,
  797. Region: config.Region
  798. }, function(err, data) {
  799. logger.log('listBucketInventory:', err || JSON.stringify(data));
  800. });
  801. }
  802. function putBucketEncryption() {
  803. cos.putBucketEncryption({
  804. Bucket: config.Bucket,
  805. Region: config.Region,
  806. ServerSideEncryptionConfiguration: {
  807. Rule: [{
  808. ApplySideEncryptionConfiguration: {
  809. SSEAlgorithm: 'AES256',
  810. },
  811. }],
  812. },
  813. }, function(err, data) {
  814. logger.log('putBucketEncryption:', err || JSON.stringify(data));
  815. });
  816. }
  817. function getBucketEncryption() {
  818. cos.getBucketEncryption({
  819. Bucket: config.Bucket,
  820. Region: config.Region
  821. }, function(err, data) {
  822. logger.log('getBucketEncryption:', err || JSON.stringify(data));
  823. });
  824. }
  825. function deleteBucketEncryption() {
  826. cos.deleteBucketEncryption({
  827. Bucket: config.Bucket,
  828. Region: config.Region
  829. }, function(err, data) {
  830. logger.log('deleteBucketEncryption:', err || JSON.stringify(data));
  831. });
  832. }
  833. function putObject() {
  834. // 创建测试文件
  835. var filename = '1mb.zip';
  836. var blob = util.createFile({size: 1024 * 1024 * 1});
  837. // 调用方法
  838. cos.putObject({
  839. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  840. Region: config.Region,
  841. Key: filename, /* 必须 */
  842. Body: blob,
  843. onTaskReady: function (tid) {
  844. TaskId = tid;
  845. logger.log('onTaskReady', tid);
  846. },
  847. onTaskStart: function (info) {
  848. logger.log('onTaskStart', info);
  849. },
  850. onProgress: function (progressData) {
  851. logger.log(JSON.stringify(progressData));
  852. },
  853. Headers: {
  854. // 万象持久化接口,上传时持久化
  855. // 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
  856. },
  857. }, function (err, data) {
  858. logger.log('putObject:', err || data);
  859. });
  860. }
  861. // 简单上传 文件boby为base64
  862. function putObject_base64ToBlob() {
  863. var base64Url = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAABRFBMVEUAAAAAo/8Ao/8Ao/8Ao/8ApP8Aov8Ao/8Abv8Abv8AyNwAyNwAo/8Ao/8Ao/8Abv8Ao/8AivgAo/8AyNwAbv8Abv8AydwApf8Abf8Ao/8AbP8Ao/8AyNwAydwAbv8AydwApP8Ao/8AyNwAo/8AyNwAydsAyNwAxd8Aov8AyNwAytsAo/8Abv8AyNwAbv8Av+MAo/8AytsAo/8Abv8AyNwAo/8Abv8AqfkAbv8Aov8Abv8AyNwAov8Abv8Ao/8Abv8Ao/8AydwAo/8Ao/8Ate8Ay9oAvOcAof8AveAAyNwAyNwAo/8AyNwAy9kAo/8AyNwAyNwAo/8AqP8Aaf8AyNwAbv0Abv8Abv8AaP8Ao/8Ao/8Ao/8Ao/8Abv8AyNwAgvcAaP8A0dkAo/8AyNwAav8Abv8Ao/8Abv8AyNwAy9sAvOUAtePdkYxjAAAAZnRSTlMAw/co8uAuJAn8+/Tt29R8DAX77+nZz87Jv6CTh3lxTklAPjouJRsL5tjAuLiyr62roaCakYp0XVtOQTMyLiohICAcGRP49vTv5+PJurawq6mnnJuYl4+OiIB7eXVvX15QSDgqHxNcw3l6AAABe0lEQVQ4y82P11oCQQxGIy5FUJpKk6aAhV6k92LvvXedDfj+92ZkYQHxnnMxu3/OfJMEJo6y++baXf5XVw22GVGcsRmq431mQZRYyIzRGgdXi+HwIv86NDBKisrRAtU1hSj9pkZ9jpo/9YKbRsmNNKCHDXI00BxfMMirKNpMcjQ5Lm4/YZArUXyBYUwg40nsdr5jb3LBe25VWpNeKa1GENsEnq52C80z1uW48estiKjb19G54QdCrScnKAU69U3KJ4jzrsBawDWPuOcBqMyRvlcb1Y+zjMUBVsivAKe4gXgEKiVjSh9wlunGMmwiOqFL3RI0cj+nkgp3jC1BELVFkGiZSuvkp3tZZWZ2sKCuDj185PXqfmwI7AAOUctHkJoOeXg3sxA4ES+l7CVvrYHMEmNp8GtR+wycPG0+1RrwWQUzl4CvgQmPP5Ddofl8tWkJVT7J+BIAaxEktrYZoRAUfXgOGYHfcOqw3WF/EdLccz5cMfvUCPb4QwUmhB8+v12HZPCkbgAAAABJRU5ErkJggg==';
  864. var dataURLtoBlob = function (dataurl) {
  865. var arr = dataurl.split(',');
  866. var mime = arr[0].match(/:(.*?);/)[1];
  867. var bstr = atob(arr[1]);
  868. var n = bstr.length;
  869. var u8arr = new Uint8Array(n);
  870. while (n--) {
  871. u8arr[n] = bstr.charCodeAt(n);
  872. }
  873. return new Blob([u8arr], { type: mime });
  874. };
  875. // 调用方法
  876. cos.putObject({
  877. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  878. Region: config.Region,
  879. Key: 'base64_file.png', /* 必须 */
  880. Body: dataURLtoBlob(base64Url),
  881. onTaskReady: function (tid) {
  882. logger.log('onTaskReady', tid);
  883. },
  884. onTaskStart: function (info) {
  885. logger.log('onTaskStart', info);
  886. },
  887. onProgress: function (progressData) {
  888. logger.log(JSON.stringify(progressData));
  889. },
  890. Headers: {
  891. // 万象持久化接口,上传时持久化
  892. // 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
  893. },
  894. }, function (err, data) {
  895. logger.log('putObject:', err || data);
  896. });
  897. }
  898. function appendObject() {
  899. cos.appendObject({
  900. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  901. Region: config.Region,
  902. Key: 'append.txt', /* 必须 */
  903. Body: '12345',
  904. Position: 0,
  905. },
  906. function(err, data) {
  907. logger.log('putObject:', err || data);
  908. })
  909. }
  910. function appendObject_continue() {
  911. cos.headObject({
  912. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  913. Region: config.Region,
  914. Key: 'append.txt', /* 必须 */
  915. }, function(err, data) {
  916. if (err) return console.log(err);
  917. // 首先取到要追加的文件当前长度,即需要上送的Position
  918. var position = data.headers['content-length'];
  919. cos.appendObject({
  920. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  921. Region: config.Region,
  922. Key: 'append.txt', /* 必须 */
  923. Body: '66666',
  924. Position: position,
  925. },
  926. function(err, data) {
  927. // 也可以取到下一次上传的position继续追加上传
  928. // var nextPosition = data.headers['x-cos-next-append-position'];
  929. logger.log('putObject:', err || data);
  930. })
  931. });
  932. }
  933. function putObjectCopy() {
  934. cos.putObjectCopy({
  935. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  936. Region: config.Region,
  937. Key: '1mb.copy.zip',
  938. CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + camSafeUrlEncode('1mb.zip').replace(/%2F/g, '/'), // Bucket 格式:test-1250000000
  939. }, function (err, data) {
  940. logger.log('putObjectCopy:', err || data);
  941. });
  942. }
  943. function getObject() {
  944. cos.getObject({
  945. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  946. Region: config.Region,
  947. Key: '1mb.zip',
  948. onProgress: function (progressData) {
  949. logger.log(JSON.stringify(progressData));
  950. }
  951. }, function (err, data) {
  952. logger.log('getObject:', err || data);
  953. });
  954. }
  955. function headObject() {
  956. cos.headObject({
  957. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  958. Region: config.Region,
  959. Key: '1mb.zip'
  960. }, function (err, data) {
  961. logger.log('headObject:', err || data);
  962. });
  963. }
  964. function putObjectAcl() {
  965. cos.putObjectAcl({
  966. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  967. Region: config.Region,
  968. Key: '1mb.zip',
  969. // GrantFullControl: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  970. // GrantWrite: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  971. // GrantRead: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
  972. // ACL: 'public-read-write',
  973. // ACL: 'public-read',
  974. // ACL: 'private',
  975. ACL: 'default', // 继承上一级目录权限
  976. // AccessControlPolicy: {
  977. // "Owner": { // AccessControlPolicy 里必须有 owner
  978. // "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 Bucket 所属用户的 QQ 号
  979. // },
  980. // "Grants": [{
  981. // "Grantee": {
  982. // "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  983. // },
  984. // "Permission": "READ"
  985. // }]
  986. // }
  987. }, function (err, data) {
  988. logger.log('putObjectAcl:', err || data);
  989. });
  990. }
  991. function getObjectAcl() {
  992. cos.getObjectAcl({
  993. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  994. Region: config.Region,
  995. Key: '1mb.zip'
  996. }, function (err, data) {
  997. logger.log('getObjectAcl:', err || data);
  998. });
  999. }
  1000. function deleteObject() {
  1001. cos.deleteObject({
  1002. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1003. Region: config.Region,
  1004. Key: '1mb.zip'
  1005. }, function (err, data) {
  1006. logger.log('deleteObject:', err || data);
  1007. });
  1008. }
  1009. function deleteMultipleObject() {
  1010. cos.deleteMultipleObject({
  1011. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1012. Region: config.Region,
  1013. Objects: [
  1014. {Key: '中文/中文.txt'},
  1015. {Key: '中文/中文.zip',VersionId: 'MTg0NDY3NDI1MzM4NzM0ODA2MTI'},
  1016. ]
  1017. }, function (err, data) {
  1018. logger.log('deleteMultipleObject:', err || data);
  1019. });
  1020. }
  1021. function restoreObject() {
  1022. cos.restoreObject({
  1023. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1024. Region: config.Region,
  1025. Key: '1.txt',
  1026. RestoreRequest: {
  1027. Days: 1,
  1028. CASJobParameters: {
  1029. Tier: 'Expedited'
  1030. }
  1031. }
  1032. }, function (err, data) {
  1033. logger.log('restoreObject:', err || data);
  1034. });
  1035. }
  1036. function selectObjectContent() {
  1037. // 查询 CSV
  1038. cos.selectObjectContent({
  1039. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1040. Region: config.Region,
  1041. Key: '1.csv',
  1042. SelectType: 2,
  1043. SelectRequest: {
  1044. Expression: "Select * from COSObject",
  1045. ExpressionType: "SQL",
  1046. InputSerialization: {
  1047. CSV: {
  1048. FileHeaderInfo: "IGNORE",
  1049. RecordDelimiter: "\\n",
  1050. FieldDelimiter: ",",
  1051. QuoteCharacter: "\"",
  1052. QuoteEscapeCharacter: "\"",
  1053. Comments: "#",
  1054. AllowQuotedRecordDelimiter: "FALSE"
  1055. }
  1056. },
  1057. OutputSerialization: {
  1058. CSV: {
  1059. QuoteFields: "ASNEEDED",
  1060. RecordDelimiter: "\\n",
  1061. FieldDelimiter: ",",
  1062. QuoteCharacter: "\"",
  1063. QuoteEscapeCharacter: "\""
  1064. }
  1065. },
  1066. RequestProgress: {
  1067. Enabled: "FALSE"
  1068. }
  1069. },
  1070. }, function (err, data) {
  1071. logger.log('selectObjectContent:', err || data);
  1072. });
  1073. // 查询 JSON
  1074. cos.selectObjectContent({
  1075. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1076. Region: config.Region,
  1077. Key: '1.json',
  1078. SelectType: 2,
  1079. SelectRequest: {
  1080. Expression: "Select b from COSObject",
  1081. ExpressionType: "SQL",
  1082. InputSerialization: {
  1083. JSON: {
  1084. Type: "DOCUMENT",
  1085. },
  1086. },
  1087. OutputSerialization: {
  1088. JSON: {
  1089. RecordDelimiter: "\n"
  1090. },
  1091. },
  1092. RequestProgress: {
  1093. Enabled: "FALSE"
  1094. }
  1095. },
  1096. }, function (err, data) {
  1097. logger.log('selectObjectContent:', err || data);
  1098. });
  1099. }
  1100. function abortUploadTask() {
  1101. cos.abortUploadTask({
  1102. Bucket: config.Bucket, /* 必须 */ // Bucket 格式:test-1250000000
  1103. Region: config.Region, /* 必须 */
  1104. // 格式1,删除单个上传任务
  1105. // Level: 'task',
  1106. // Key: '10mb.zip',
  1107. // UploadId: '14985543913e4e2642e31db217b9a1a3d9b3cd6cf62abfda23372c8d36ffa38585492681e3',
  1108. // 格式2,删除单个文件所有未完成上传任务
  1109. Level: 'file',
  1110. Key: '10mb.zip',
  1111. // 格式3,删除 Bucket 下所有未完成上传任务
  1112. // Level: 'bucket',
  1113. }, function (err, data) {
  1114. logger.log('abortUploadTask:', err || data);
  1115. });
  1116. }
  1117. function uploadFile() {
  1118. var filename = '10mb.zip';
  1119. var blob = util.createFile({size: 1024 * 1024 * 10});
  1120. cos.uploadFile({
  1121. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1122. Region: config.Region,
  1123. Key: filename,
  1124. Body: blob,
  1125. SliceSize: 1024 * 1024 * 5, // 大于5mb才进行分块上传
  1126. onProgress: function (info) {
  1127. var percent = Math.floor(info.percent * 10000) / 100;
  1128. var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
  1129. logger.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;');
  1130. },
  1131. }, function (err, data) {
  1132. logger.log('上传' + (err ? '失败' : '完成'));
  1133. logger.log('uploadFile:', err || data);
  1134. });
  1135. }
  1136. function sliceUploadFile() {
  1137. var blob = util.createFile({size: 1024 * 1024 * 3});
  1138. cos.sliceUploadFile({
  1139. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1140. Region: config.Region,
  1141. Key: '3mb.zip', /* 必须 */
  1142. Body: blob,
  1143. Headers: {
  1144. // 万象持久化接口,上传时持久化
  1145. // 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
  1146. },
  1147. onTaskReady: function (tid) {
  1148. TaskId = tid;
  1149. },
  1150. onHashProgress: function (progressData) {
  1151. logger.log('onHashProgress', JSON.stringify(progressData));
  1152. },
  1153. onProgress: function (progressData) {
  1154. logger.log('onProgress', JSON.stringify(progressData));
  1155. },
  1156. }, function (err, data) {
  1157. logger.log('sliceUploadFile:', err || data);
  1158. });
  1159. }
  1160. function selectFileToUpload() {
  1161. util.selectLocalFile(function (files) {
  1162. var file = files && files[0];
  1163. if (!file) return;
  1164. if (file.size > 1024 * 1024) {
  1165. cos.sliceUploadFile({
  1166. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1167. Region: config.Region,
  1168. Key: file.name,
  1169. Body: file,
  1170. onTaskReady: function (tid) {
  1171. TaskId = tid;
  1172. },
  1173. onHashProgress: function (progressData) {
  1174. logger.log('onHashProgress', JSON.stringify(progressData));
  1175. },
  1176. onProgress: function (progressData) {
  1177. logger.log('onProgress', JSON.stringify(progressData));
  1178. },
  1179. }, function (err, data) {
  1180. logger.log('selectFileToUpload:', err || data);
  1181. });
  1182. } else {
  1183. cos.putObject({
  1184. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1185. Region: config.Region,
  1186. Key: file.name,
  1187. Body: file,
  1188. onTaskReady: function (tid) {
  1189. TaskId = tid;
  1190. },
  1191. onHashProgress: function (progressData) {
  1192. logger.log('onHashProgress', JSON.stringify(progressData));
  1193. },
  1194. onProgress: function (progressData) {
  1195. logger.log(JSON.stringify(progressData));
  1196. },
  1197. }, function (err, data) {
  1198. logger.log('selectFileToUpload:', err || data);
  1199. });
  1200. }
  1201. });
  1202. }
  1203. function cancelTask() {
  1204. cos.cancelTask(TaskId);
  1205. logger.log('canceled');
  1206. }
  1207. function pauseTask() {
  1208. cos.pauseTask(TaskId);
  1209. logger.log('paused');
  1210. }
  1211. function restartTask() {
  1212. cos.restartTask(TaskId);
  1213. logger.log('restart');
  1214. }
  1215. function uploadFiles() {
  1216. var filename = 'mb.zip';
  1217. var blob = util.createFile({size: 1024 * 1024 * 10});
  1218. cos.uploadFiles({
  1219. files: [{
  1220. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1221. Region: config.Region,
  1222. Key: '1' + filename,
  1223. Body: blob,
  1224. }, {
  1225. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1226. Region: config.Region,
  1227. Key: '2' + filename,
  1228. Body: blob,
  1229. }, {
  1230. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1231. Region: config.Region,
  1232. Key: '3' + filename,
  1233. Body: blob,
  1234. }],
  1235. SliceSize: 1024 * 1024,
  1236. onProgress: function (info) {
  1237. var percent = Math.floor(info.percent * 10000) / 100;
  1238. var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
  1239. logger.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;');
  1240. },
  1241. onFileFinish: function (err, data, options) {
  1242. logger.log(options.Key + ' 上传' + (err ? '失败' : '完成'));
  1243. },
  1244. }, function (err, data) {
  1245. logger.log('uploadFiles:', err || data);
  1246. });
  1247. }
  1248. function sliceCopyFile() {
  1249. // 创建测试文件
  1250. var sourceName = '3mb.zip';
  1251. var Key = '3mb.copy.zip';
  1252. var sourcePath = config.Bucket + '.cos.' + config.Region + '.myqcloud.com/'+ camSafeUrlEncode(sourceName).replace(/%2F/g, '/');
  1253. cos.sliceCopyFile({
  1254. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1255. Region: config.Region,
  1256. Key: Key,
  1257. CopySource: sourcePath,
  1258. SliceSize: 2 * 1024 * 1024, // 大于2M的文件用分片复制,小于则用单片复制
  1259. onProgress:function (info) {
  1260. var percent = Math.floor(info.percent * 10000) / 100;
  1261. var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
  1262. logger.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;');
  1263. }
  1264. },function (err,data) {
  1265. if(err){
  1266. logger.log('sliceCopyFile:', err);
  1267. }else{
  1268. logger.log('sliceCopyFile:', data);
  1269. }
  1270. });
  1271. }
  1272. /* 移动对象*/
  1273. function moveObject() {
  1274. // COS 没有对象重命名或移动的接口,移动对象可以通过复制/删除对象实现
  1275. var source = 'source.txt';
  1276. var target = 'target.txt';
  1277. var copySource = config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + camSafeUrlEncode(source).replace(/%2F/g, '/');
  1278. cos.putObject({
  1279. Bucket: config.Bucket,
  1280. Region: config.Region,
  1281. Key: source,
  1282. Body: 'hello!',
  1283. }, function (err, data) {
  1284. if (err) return logger.log(err);
  1285. cos.putObjectCopy({
  1286. Bucket: config.Bucket,
  1287. Region: config.Region,
  1288. Key: target,
  1289. CopySource: copySource,
  1290. }, function (err, data) {
  1291. if (err) return logger.log(err);
  1292. cos.deleteObject({
  1293. Bucket: config.Bucket,
  1294. Region: config.Region,
  1295. Key: source,
  1296. }, function (err, data) {
  1297. logger.log(err || data);
  1298. });
  1299. });
  1300. });
  1301. }
  1302. /* 上传到指定文件夹/目录 */
  1303. function uploadToFolder() {
  1304. util.selectLocalFile(function (files) {
  1305. var file = files && files[0];
  1306. if (!file) return;
  1307. cos.putObject({
  1308. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1309. Region: config.Region,
  1310. Key: 'folder/' + file.name,
  1311. Body: file,
  1312. }, function (err, data) {
  1313. logger.log(err || data);
  1314. });
  1315. });
  1316. }
  1317. /* 创建文件夹 */
  1318. function createFolder() {
  1319. cos.putObject({
  1320. Bucket: config.Bucket,
  1321. Region: config.Region,
  1322. Key: 'folder/', // 对象存储没有实际的文件夹,可以创建一个路径以 / 结尾的空对象表示,能在部分场景中满足文件夹使用需要
  1323. Body: '',
  1324. }, function(err, data) {
  1325. logger.log(err || data);
  1326. });
  1327. }
  1328. /* 上传本地文件夹 */
  1329. function uploadFolder() {
  1330. // <input type='file' name="file" webkitdirectory >
  1331. var input = document.createElement('input');
  1332. input.type = 'file';
  1333. input.webkitdirectory = true;
  1334. input.onchange = function(){
  1335. var oFiles = input.files;
  1336. if (!oFiles.length) return;
  1337. var files = [];
  1338. for (var i = 0; i < oFiles.length; i++) {
  1339. var file = oFiles[i];
  1340. var Key = 'folder/' + file.webkitRelativePath;
  1341. files.push({
  1342. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1343. Region: config.Region,
  1344. Key: Key,
  1345. Body: file,
  1346. });
  1347. }
  1348. cos.uploadFiles({
  1349. files: files,
  1350. SliceSize: 1024 * 1024,
  1351. onProgress: function (info) {
  1352. var percent = Math.floor(info.percent * 10000) / 100;
  1353. var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
  1354. logger.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;');
  1355. },
  1356. onFileFinish: function (err, data, options) {
  1357. logger.log(options.Key + ' 上传' + (err ? '失败' : '完成'));
  1358. },
  1359. }, function (err, data) {
  1360. logger.log('uploadFolder:', err || data);
  1361. });
  1362. };
  1363. input.click();
  1364. }
  1365. /* 列出文件夹下的文件 */
  1366. function listFolder() {
  1367. var _listFolder = function(params, callback) {
  1368. var Contents = [];
  1369. var CommonPrefixes = [];
  1370. var marker;
  1371. var next = function() {
  1372. params.Marker = marker;
  1373. cos.getBucket(params, function(err, data) {
  1374. if (err) return callback(err);
  1375. data && data.CommonPrefixes && data.CommonPrefixes.forEach(function (item) {
  1376. CommonPrefixes.push(item);
  1377. });
  1378. data && data.Contents && data.Contents.forEach(function (item) {
  1379. Contents.push(item);
  1380. });
  1381. if (data.IsTruncated === 'true') {
  1382. marker = data.NextMarker;
  1383. next();
  1384. } else {
  1385. callback(null, {
  1386. CommonPrefixes: CommonPrefixes,
  1387. Contents: Contents,
  1388. });
  1389. }
  1390. });
  1391. };
  1392. next();
  1393. };
  1394. _listFolder({
  1395. Bucket: config.Bucket,
  1396. Region: config.Region,
  1397. Delimiter: '/', // 如果按目录列出文件传入该分隔符,如果要深度列出文件不传改参数
  1398. Prefix: 'folder/', // 要列出的目录前缀
  1399. }, function (err, data) {
  1400. logger.log('listFolder:', err || data);
  1401. });
  1402. }
  1403. /* 删除指定文件夹下的所有对象(删除存储桶里指定前缀所有对象) */
  1404. function deleteFolder() {
  1405. var _deleteFolder = function(params, callback) {
  1406. var deletedList = [];
  1407. var errorList = [];
  1408. var marker;
  1409. var next = function() {
  1410. params.Marker = marker;
  1411. cos.getBucket(params, function(err, data) {
  1412. if (err) return callback(err);
  1413. var Objects = [];
  1414. if (data && data.Contents && data.Contents.length) {
  1415. data.Contents.forEach(function (item) {
  1416. Objects.push({Key: item.Key});
  1417. });
  1418. }
  1419. var afterDeleted = function () {
  1420. if (data.IsTruncated === 'true') {
  1421. marker = data.NextMarker;
  1422. next();
  1423. } else {
  1424. callback(null, { Deleted: deletedList, Error: errorList });
  1425. }
  1426. };
  1427. if (Objects.length) {
  1428. cos.deleteMultipleObject({
  1429. Bucket: params.Bucket,
  1430. Region: params.Region,
  1431. Objects: Objects,
  1432. }, function (err, data) {
  1433. data.Deleted && data.Deleted.forEach(function (item) {
  1434. deletedList.push(item);
  1435. });
  1436. data.Error && data.Error.forEach(function (item) {
  1437. errorList.push(item);
  1438. });
  1439. afterDeleted();
  1440. });
  1441. } else {
  1442. afterDeleted();
  1443. }
  1444. });
  1445. };
  1446. next();
  1447. };
  1448. _deleteFolder({
  1449. Bucket: config.Bucket,
  1450. Region: config.Region,
  1451. Prefix: 'folder/', // 要列出的目录前缀
  1452. }, function (err, data) {
  1453. logger.log('deleteFolder:', err || data);
  1454. });
  1455. }
  1456. function request() {
  1457. cos.request({
  1458. Bucket: config.Bucket,
  1459. Region: config.Region,
  1460. Key: '1.png',
  1461. Method: 'POST',
  1462. Action: 'image_process',
  1463. Headers: {
  1464. // 通过 imageMogr2 接口使用图片缩放功能:指定图片宽度为 200,宽度等比压缩
  1465. 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule": "imageMogr2/thumbnail/200x/"}]}'
  1466. },
  1467. }, function (err, data) {
  1468. logger.log('request:', err || data);
  1469. });
  1470. }
  1471. function CIExample1(){
  1472. util.selectLocalFile(function (files) {
  1473. var file = files && files[0];
  1474. if (!file) return;
  1475. if(file.type.indexOf('image') < 0){
  1476. logger.error('Please select a photo to upload!');
  1477. return;
  1478. }
  1479. if (file.size > 1024 * 1024) {
  1480. cos.sliceUploadFile({
  1481. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1482. Region: config.Region,
  1483. Key: file.name,
  1484. Body: file,
  1485. Headers: {
  1486. // 通过 imageMogr2 接口使用图片缩放功能:指定图片宽度为 200,宽度等比压缩
  1487. 'Pic-Operations':
  1488. '{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule": "imageMogr2/thumbnail/200x/"}]}',
  1489. },
  1490. onTaskReady: function (tid) {
  1491. TaskId = tid;
  1492. },
  1493. onHashProgress: function (progressData) {
  1494. logger.log('onHashProgress', JSON.stringify(progressData));
  1495. },
  1496. onProgress: function (progressData) {
  1497. logger.log('onProgress', JSON.stringify(progressData));
  1498. },
  1499. }, function (err, data) {
  1500. logger.log('CIExample1:', err || data);
  1501. });
  1502. } else {
  1503. cos.putObject({
  1504. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  1505. Region: config.Region,
  1506. Key: file.name,
  1507. Body: file,
  1508. Headers: {
  1509. // 通过 imageMogr2 接口使用图片缩放功能:指定图片宽度为 200,宽度等比压缩
  1510. 'Pic-Operations':
  1511. '{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule": "imageMogr2/thumbnail/200x/"}]}',
  1512. },
  1513. onTaskReady: function (tid) {
  1514. TaskId = tid;
  1515. },
  1516. onHashProgress: function (progressData) {
  1517. logger.log('onHashProgress', JSON.stringify(progressData));
  1518. },
  1519. onProgress: function (progressData) {
  1520. logger.log('onProgress', JSON.stringify(progressData));
  1521. },
  1522. }, function (err, data) {
  1523. logger.log('CIExample1:', err || data);
  1524. });
  1525. }
  1526. });
  1527. }
  1528. function CIExample2(){
  1529. cos.request({
  1530. Bucket: config.Bucket,
  1531. Region: config.Region,
  1532. Key: 'photo.png',
  1533. Method: 'POST',
  1534. Action: 'image_process',
  1535. Headers: {
  1536. // 通过 imageMogr2 接口使用图片缩放功能:指定图片宽度为 200,宽度等比压缩
  1537. 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule": "imageMogr2/thumbnail/200x/"}]}'
  1538. },
  1539. }, function (err, data) {
  1540. logger.log('CIExample2:', err || data);
  1541. });
  1542. }
  1543. function CIExample3(){
  1544. cos.getObject({
  1545. Bucket: config.Bucket,
  1546. Region: config.Region,
  1547. Key: 'photo.png',
  1548. QueryString: `imageMogr2/thumbnail/200x/`,
  1549. },
  1550. function (err, data) {
  1551. logger.log('CIExample3:', err || data);
  1552. },
  1553. );
  1554. }
  1555. function CIExample4(){
  1556. // 生成带图片处理参数的文件签名URL,过期时间设置为 30 分钟。
  1557. cos.getObjectUrl({
  1558. Bucket: config.Bucket,
  1559. Region: config.Region,
  1560. Key: 'photo.png',
  1561. QueryString: `imageMogr2/thumbnail/200x/`,
  1562. Expires: 1800,
  1563. Sign: true,
  1564. },
  1565. function (err, data) {
  1566. logger.log('getObjectUrl with sign: ', err || data && data.Url);
  1567. },
  1568. );
  1569. // 生成带图片处理参数的文件URL,不带签名。
  1570. cos.getObjectUrl({
  1571. Bucket: config.Bucket,
  1572. Region: config.Region,
  1573. Key: 'photo.png',
  1574. QueryString: `imageMogr2/thumbnail/200x/`,
  1575. Sign: false,
  1576. },
  1577. function (err, data) {
  1578. logger.log('getObjectUrl without sign: ', err || data && data.Url);
  1579. },
  1580. );
  1581. }
  1582. // 查询已经开通数据万象功能的存储桶
  1583. function describeMediaBuckets() {
  1584. var host = 'ci.' + config.Region + '.myqcloud.com';
  1585. var url = 'https://' + host + '/mediabucket';
  1586. cos.request({
  1587. Bucket: config.Bucket,
  1588. Region: config.Region,
  1589. Method: 'GET',
  1590. Key: 'mediabucket', /** 固定值,必须 */
  1591. Url: url,
  1592. Query: {
  1593. pageNumber: '1', /** 第几页,非必须 */
  1594. pageSize: '10', /** 每页个数,非必须 */
  1595. // regions: 'ap-chengdu', /** 地域信息,例如'ap-beijing',支持多个值用逗号分隔如'ap-shanghai,ap-beijing',非必须 */
  1596. // bucketNames: 'test-1250000000', /** 存储桶名称,精确搜索,例如'test-1250000000',支持多个值用逗号分隔如'test1-1250000000,test2-1250000000',非必须 */
  1597. // bucketName: 'test', /** 存储桶名称前缀,前缀搜索,例如'test',支持多个值用逗号分隔如'test1,test2',非必须 */
  1598. }
  1599. }, function (err, data) {
  1600. logger.log(err || data);
  1601. });
  1602. }
  1603. // 获取媒体文件信息
  1604. function getMediaInfo() {
  1605. cos.request({
  1606. Bucket: config.Bucket,
  1607. Region: config.Region,
  1608. Method: 'GET',
  1609. Key: 'test.mp4',
  1610. Query: {
  1611. 'ci-process': 'videoinfo' /** 固定值,必须 */
  1612. }
  1613. }, function (err, data) {
  1614. logger.log(err || data);
  1615. });
  1616. }
  1617. // 获取媒体文件某个时间的截图
  1618. function getSnapshot() {
  1619. cos.request({
  1620. Bucket: config.Bucket,
  1621. Region: config.Region,
  1622. Method: 'GET',
  1623. Key: 'test.mp4',
  1624. Query: {
  1625. 'ci-process': 'snapshot', /** 固定值,必须 */
  1626. time: 1, /** 截图的时间点,单位为秒,必须 */
  1627. // width: 0, /** 截图的宽,非必须 */
  1628. // height: 0, /** 截图的高,非必须 */
  1629. // format: 'jpg', /** 截图的格式,支持 jpg 和 png,默认 jpg,非必须 */
  1630. // rotate: 'auto', /** 图片旋转方式,默认为'auto',非必须 */
  1631. // mode: 'exactframe', /** 截帧方式,默认为'exactframe',非必须 */
  1632. },
  1633. RawBody: true,
  1634. },
  1635. function(err, data){
  1636. logger.log(err || data);
  1637. });
  1638. }
  1639. (function () {
  1640. var list = [
  1641. 'header-工具函数',
  1642. 'request',
  1643. 'getObjectUrl',
  1644. 'getAuth',
  1645. //'getService', // 不支持,正常场景会跨域
  1646. 'header-存储桶操作',
  1647. //'putBucket', // 不支持,正常场景会跨域
  1648. 'headBucket',
  1649. 'putBucketAcl',
  1650. 'getBucketAcl',
  1651. 'putBucketCors',
  1652. 'getBucketCors',
  1653. // 'deleteBucketCors', // 不建议调用,删除 CORS,浏览器不能正常调用
  1654. 'putBucketTagging',
  1655. 'getBucketTagging',
  1656. 'deleteBucketTagging',
  1657. 'putBucketPolicy',
  1658. 'getBucketPolicy',
  1659. 'deleteBucketPolicy',
  1660. 'getBucketLocation',
  1661. 'getBucketLifecycle',
  1662. 'putBucketLifecycle',
  1663. 'deleteBucketLifecycle',
  1664. 'putBucketVersioning',
  1665. 'getBucketVersioning',
  1666. 'getBucketReplication',
  1667. 'putBucketReplication',
  1668. 'deleteBucketReplication',
  1669. 'putBucketWebsite',
  1670. 'getBucketWebsite',
  1671. 'deleteBucketWebsite',
  1672. 'putBucketReferer',
  1673. 'getBucketReferer',
  1674. 'putBucketDomain',
  1675. 'getBucketDomain',
  1676. 'deleteBucketDomain',
  1677. 'putBucketLogging',
  1678. 'getBucketLogging',
  1679. 'deleteBucketLogging',
  1680. 'putBucketInventory',
  1681. 'getBucketInventory',
  1682. 'deleteBucketInventory',
  1683. 'listBucketInventory',
  1684. 'putBucketEncryption',
  1685. 'getBucketEncryption',
  1686. 'deleteBucketEncryption',
  1687. 'deleteBucket',
  1688. 'header-对象操作',
  1689. 'getBucket',
  1690. 'listObjectVersions',
  1691. 'putObjectCopy',
  1692. 'getObject',
  1693. 'headObject',
  1694. 'putObjectAcl',
  1695. 'getObjectAcl',
  1696. 'deleteObject',
  1697. 'deleteMultipleObject',
  1698. 'restoreObject',
  1699. 'abortUploadTask',
  1700. 'selectObjectContent',
  1701. 'putObject',
  1702. 'putObject_base64ToBlob',
  1703. 'appendObject',
  1704. 'appendObject_continue',
  1705. 'header-高级操作',
  1706. 'uploadFile',
  1707. 'sliceUploadFile',
  1708. 'selectFileToUpload',
  1709. 'sliceCopyFile',
  1710. 'uploadFiles',
  1711. 'uploadFolder',
  1712. 'uploadToFolder',
  1713. 'moveObject',
  1714. 'createFolder',
  1715. 'listFolder',
  1716. 'deleteFolder',
  1717. 'cancelTask',
  1718. 'pauseTask',
  1719. 'restartTask',
  1720. 'header-数据万象示例',
  1721. 'CIExample1',
  1722. 'CIExample2',
  1723. 'CIExample3',
  1724. 'CIExample4',
  1725. 'describeMediaBuckets',
  1726. 'getMediaInfo',
  1727. 'getSnapshot',
  1728. ];
  1729. var labelMap = {
  1730. putObject: '简单上传',
  1731. putObject_base64ToBlob: '简单上传:base64转blob',
  1732. appendObject: '追加上传',
  1733. appendObject_continue: '查询position并追加上传',
  1734. uploadFile: '高级上传',
  1735. sliceUploadFile: '分片上传',
  1736. sliceCopyFile: '分片复制',
  1737. uploadFiles: '批量上传文件',
  1738. selectFileToUpload: '上传本地文件',
  1739. uploadFolder: '上传文件夹',
  1740. uploadToFolder: '上传到指定文件夹',
  1741. request: '通用请求接口',
  1742. listFolder: '列出文件夹',
  1743. deleteFolder: '删除文件夹(按前缀批量删除)',
  1744. CIExample1: '上传时使用图片处理',
  1745. CIExample2: '对云上数据进行图片处理',
  1746. CIExample3: '下载时使用图片处理',
  1747. CIExample4: '生成带图片处理参数的签名 URL',
  1748. describeMediaBuckets: '查询媒体处理开通情况',
  1749. getMediaInfo: '获取媒体文件信息',
  1750. getSnapshot: '获取媒体文件某个时间的截图',
  1751. };
  1752. var container = document.querySelector('.main');
  1753. var html = [];
  1754. list.forEach(function (name) {
  1755. if (name === '-') {
  1756. html.push('<hr/>');
  1757. } else if(name.indexOf('header') > -1){
  1758. html.push('<h4>'+ name.split('-')[1] +'</h4>')
  1759. } else {
  1760. html.push('<a href="javascript:void(0)" data-method="' + name + '">' + name + (labelMap[name] ? ' (' + labelMap[name] + ')' : '') + '</a>');
  1761. }
  1762. });
  1763. container.innerHTML = html.join('');
  1764. container.onclick = function (e) {
  1765. if (e.target.tagName === 'A') {
  1766. var name = e.target.getAttribute('data-method').trim();
  1767. window[name]();
  1768. }
  1769. };
  1770. // 设置结果面板跟随窗口自适应高
  1771. var mainPanel = document.querySelector('.main');
  1772. var resultPanel = document.querySelector('.result');
  1773. resultPanel.style.height = getPanelHeight();
  1774. window.onresize = function(e){
  1775. resultPanel.style.height = getPanelHeight();
  1776. }
  1777. function getPanelHeight(){
  1778. return (mainPanel.getBoundingClientRect().height - 80) + 'px';
  1779. }
  1780. })();