demo.js 73 KB

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