forked from tencentyun/cos-js-sdk-v5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.js
1782 lines (1678 loc) · 59.6 KB
/
demo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
var config = {
Bucket: 'test-1250000000',
Region: 'ap-guangzhou'
};
var util = {
createFile: function (options) {
var buffer = new ArrayBuffer(options.size || 0);
var arr = new Uint8Array(buffer);
[].forEach.call(arr, function (char, i) {
arr[i] = 0;
});
var opt = {};
options.type && (opt.type = options.type);
var blob = new Blob([buffer], options);
return blob;
},
selectLocalFile: function (onChange) {
var id = 'file_selector';
var input = document.createElement('input');
input.style = 'width:0;height:0;border:0;margin:0;padding:0;';
input.type = 'file';
input.id = id;
input.onchange = function (e) {
var files = this.files;
if (!files.length) return;
onChange && onChange(files);
document.body.removeChild(input);
};
document.body.appendChild(input);
input.click();
},
};
// 对更多字符编码的 url encode 格式
var camSafeUrlEncode = function (str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
};
var getAuthorization = function (options, callback) {
// 格式一、(推荐)后端通过获取临时密钥给到前端,前端计算签名
// 服务端 JS 和 PHP 例子:https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
// 服务端其他语言参考 COS STS SDK :https://github.com/tencentyun/qcloud-cos-sts-sdk
// var url = '../server/sts.php'; // 如果起的是 php server 用这个
var url = '/sts'; // 如果是 npm run sts.js 起的 nodejs server,使用这个
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
try {
var data = JSON.parse(e.target.responseText);
var credentials = data.credentials;
} catch (e) {
}
if (!data || !credentials) {
return logger.error('credentials invalid:\n' + JSON.stringify(data, null, 2))
};
var authorization = COS.getAuthorization({
SecretId: credentials.tmpSecretId, // 可传固定密钥或者临时密钥
SecretKey: credentials.tmpSecretKey, // 可传固定密钥或者临时密钥
Method: options.Method,
Pathname: options.Pathname,
Query: options.Query,
Headers: options.Headers,
Expires: 900,
});
callback({
Authorization: authorization,
XCosSecurityToken: credentials.sessionToken,
});
};
xhr.send();
// // 格式二、(推荐)【细粒度控制权限】后端通过获取临时密钥给到前端,前端只有相同请求才重复使用临时密钥,后端可以通过 Scope 细粒度控制权限
// // 服务端例子:https://github.com/tencentyun/qcloud-cos-sts-sdk/edit/master/scope.md
// // var url = '../server/sts.php'; // 如果起的是 php server 用这个
// var url = '/sts-scope'; // 如果是 npm run sts.js 起的 nodejs server,使用这个
// var xhr = new XMLHttpRequest();
// xhr.open('POST', url, true);
// xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.onload = function (e) {
// try {
// var data = JSON.parse(e.target.responseText);
// var credentials = data.credentials;
// } catch (e) {
// }
// if (!data || !credentials) {
// return logger.error('credentials invalid:\n' + JSON.stringify(data, null, 2))
// };
// callback({
// TmpSecretId: credentials.tmpSecretId,
// TmpSecretKey: credentials.tmpSecretKey,
// SecurityToken: credentials.sessionToken,
// StartTime: data.startTime, // 时间戳,单位秒,如:1580000000,建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
// ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000000
// ScopeLimit: true, // 细粒度控制权限需要设为 true,会限制密钥只在相同请求时重复使用
// });
// };
// xhr.send(JSON.stringify(options.Scope));
// // 格式三、(不推荐,分片上传权限不好控制)前端每次请求前都需要通过 getAuthorization 获取签名,后端使用固定密钥或临时密钥计算签名返回给前端
// // 服务端获取签名,请参考对应语言的 COS SDK:https://cloud.tencent.com/document/product/436/6474
// // 注意:这种有安全风险,后端需要通过 method、pathname 严格控制好权限,比如不允许 put / 等
// var method = (options.Method || 'get').toLowerCase();
// var query = options.Query || {};
// var headers = options.Headers || {};
// var pathname = options.Pathname || '/';
// // var url = 'http://127.0.0.1:3000/auth';
// var url = '../server/auth.php';
// var xhr = new XMLHttpRequest();
// var data = {
// method: method,
// pathname: pathname,
// query: query,
// headers: headers,
// };
// xhr.open('POST', url, true);
// xhr.setRequestHeader('content-type', 'application/json');
// xhr.onload = function (e) {
// try {
// var data = JSON.parse(e.target.responseText);
// } catch (e) {
// }
// if (!data || !data.authorization) return console.error('authorization invalid');
// callback({
// Authorization: data.authorization,
// // SecurityToken: data.sessionToken, // 如果使用临时密钥,需要把 sessionToken 传给 SecurityToken
// });
// };
// xhr.send(JSON.stringify(data));
// // 格式四、(不推荐,适用于前端调试,避免泄露密钥)前端使用固定密钥计算签名
// var authorization = COS.getAuthorization({
// SecretId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 可传固定密钥或者临时密钥
// SecretKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 可传固定密钥或者临时密钥
// Method: options.Method,
// Pathname: options.Pathname,
// Query: options.Query,
// Headers: options.Headers,
// Expires: 900,
// });
// callback({
// Authorization: authorization,
// // SecurityToken: credentials.sessionToken, // 如果使用临时密钥,需要传 SecurityToken
// });
};
var cos = new COS({
getAuthorization: getAuthorization,
UploadCheckContentMd5: true,
});
var TaskId;
var pre = document.querySelector('.result');
var showLogText = function (text, color) {
if (typeof text === 'object') {
try {
text = JSON.stringify(text);
} catch (e) {
}
}
var div = document.createElement('div');
div.innerText = text;
color && (div.style.color = color);
pre.appendChild(div);
pre.style.display = 'block';
pre.scrollTop = pre.scrollHeight;
};
var logger = {
log: function (text) {
console.log.apply(console, arguments);
var args = [].map.call(arguments, function (v) {
return typeof v === 'object' ? JSON.stringify(v, null, 2) : v;
});
var logStr = args.join(' ');
if(logStr.length > 1000000) {
logStr = logStr.slice(0, 1000000) + '...content is too long, the first 1000000 characters are intercepted';
}
showLogText(logStr);
},
error: function (text) {
console.error(text);
showLogText(text, 'red');
},
};
function getObjectUrl() {
var url = cos.getObjectUrl({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Key: '1mb.zip',
Expires: 60,
Sign: true,
}, function (err, data) {
logger.log('getObjectUrl:', err || data && data.Url);
});
logger.log('getObjectUrl:', url);
}
function getAuth() {
var key = '1.png';
// 这里不推荐自己拼接,推荐使用 getObjectUrl 获取 url
getAuthorization({
Method: 'get',
Key: key
}, function (AuthData) {
if (typeof AuthData === 'string') {
AuthData = {Authorization: AuthData};
}
var url = 'http://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com' + '/' +
camSafeUrlEncode(key).replace(/%2F/g, '/') +
'?' + AuthData +
(AuthData.SecurityToken ? '&' + AuthData.SecurityToken : '');
logger.log('getAuth:', url);
});
}
// getService、putBucket 接口会跨域,不支持浏览器使用,只在场景下可调用,比如改了 ServiceDomain 到代理地址
function getService() {
cos.getService(function (err, data) {
logger.log('getService:', err || data);
});
}
// getService、putBucket 接口会跨域,不支持浏览器使用,只在场景下可调用,比如改了 ServiceDomain 到代理地址
function putBucket() {
cos.putBucket({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
// Prefix: 'dir/'
// Delimiter: '/'
}, function (err, data) {
logger.log('putBucket:', err || data);
});
}
function getBucket() {
cos.getBucket({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
// Prefix: 'dir/'
// Delimiter: '/'
}, function (err, data) {
logger.log('getBucket:', err || data);
});
}
function headBucket() {
cos.headBucket({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('headBucket:', err || data);
});
}
function deleteBucket() {
cos.deleteBucket({
Bucket: 'testnew-' + config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1),
Region: 'ap-guangzhou'
}, function (err, data) {
logger.log('deleteBucket:', err || data);
});
}
function putBucketAcl() {
cos.putBucketAcl({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
// GrantFullControl: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
// GrantWrite: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
// GrantRead: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
// GrantReadAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
// GrantWriteAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
// ACL: 'public-read-write',
// ACL: 'public-read',
ACL: 'private',
// AccessControlPolicy: {
// "Owner": { // AccessControlPolicy 里必须有 owner
// "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 Bucket 所属用户的 QQ 号
// },
// "Grants": [{
// "Grantee": {
// "URI": "http://cam.qcloud.com/groups/global/AllUsers", // 允许匿名用户组访问
// },
// "Permission": "READ"
// }, {
// "Grantee": {
// "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
// },
// "Permission": "WRITE"
// }, {
// "Grantee": {
// "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
// },
// "Permission": "READ_ACP"
// }, {
// "Grantee": {
// "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
// },
// "Permission": "WRITE_ACP"
// }]
// }
}, function (err, data) {
logger.log('putBucketAcl:', err || data);
});
}
function getBucketAcl() {
cos.getBucketAcl({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketAcl:', err || data);
});
}
function putBucketCors() {
cos.putBucketCors({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
CORSRules: [{
"AllowedOrigin": ["*"],
"AllowedMethod": ["GET", "POST", "PUT", "DELETE", "HEAD"],
"AllowedHeader": ["*"],
"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"],
"MaxAgeSeconds": "5"
}]
}, function (err, data) {
logger.log('putBucketCors:', err || data);
});
}
function getBucketCors() {
cos.getBucketCors({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketCors:', err || data);
});
}
function deleteBucketCors() {
cos.deleteBucketCors({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('deleteBucketCors:', err || data);
});
}
function putBucketTagging() {
cos.putBucketTagging({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Tagging: {
"Tags": [
{"Key": "k1", "Value": "v1"},
{"Key": "k2", "Value": "v2"}
]
}
}, function (err, data) {
logger.log('putBucketTagging:', err || data);
});
}
function getBucketTagging() {
cos.getBucketTagging({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketTagging:', err || data);
});
}
function deleteBucketTagging() {
cos.deleteBucketTagging({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('deleteBucketTagging:', err || data);
});
}
function putBucketPolicy() {
var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
cos.putBucketPolicy({
Policy: {
"version": "2.0",
"statement": [{
"effect": "allow",
"principal": {"qcs": ["qcs::cam::uin/10001:uin/10001"]}, // 这里的 10001 是 QQ 号
"action": [
// 这里可以从临时密钥的权限上控制前端允许的操作
// 'name/cos:*', // 这样写可以包含下面所有权限
// // 列出所有允许的操作
// // ACL 读写
// 'name/cos:GetBucketACL',
// 'name/cos:PutBucketACL',
// 'name/cos:GetObjectACL',
// 'name/cos:PutObjectACL',
// // 简单 Bucket 操作
// 'name/cos:PutBucket',
// 'name/cos:HeadBucket',
// 'name/cos:GetBucket',
// 'name/cos:DeleteBucket',
// 'name/cos:GetBucketLocation',
// // Versioning
// 'name/cos:PutBucketVersioning',
// 'name/cos:GetBucketVersioning',
// // CORS
// 'name/cos:PutBucketCORS',
// 'name/cos:GetBucketCORS',
// 'name/cos:DeleteBucketCORS',
// // Lifecycle
// 'name/cos:PutBucketLifecycle',
// 'name/cos:GetBucketLifecycle',
// 'name/cos:DeleteBucketLifecycle',
// // Replication
// 'name/cos:PutBucketReplication',
// 'name/cos:GetBucketReplication',
// 'name/cos:DeleteBucketReplication',
// // 删除文件
// 'name/cos:DeleteMultipleObject',
// 'name/cos:DeleteObject',
// 简单文件操作
'name/cos:PutObject',
'name/cos:AppendObject',
'name/cos:GetObject',
'name/cos:HeadObject',
'name/cos:OptionsObject',
'name/cos:PutObjectCopy',
'name/cos:PostObjectRestore',
// 分片上传操作
'name/cos:InitiateMultipartUpload',
'name/cos:ListMultipartUploads',
'name/cos:ListParts',
'name/cos:UploadPart',
'name/cos:CompleteMultipartUpload',
'name/cos:AbortMultipartUpload',
],
// "resource": ["qcs::cos:ap-guangzhou:uid/1250000000:test-1250000000/*"] // 1250000000 是 appid
"resource": ["qcs::cos:" + config.Region + ":uid/" + AppId + ":" + config.Bucket + "/*"] // 1250000000 是 appid
}]
},
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('putBucketPolicy:', err || data);
});
}
function getBucketPolicy() {
cos.getBucketPolicy({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketPolicy:', err || data);
});
}
function deleteBucketPolicy() {
cos.deleteBucketPolicy({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('deleteBucketPolicy:', err || data);
});
}
function getBucketLocation() {
cos.getBucketLocation({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketLocation:', err || data);
});
}
function putBucketLifecycle() {
cos.putBucketLifecycle({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
LifecycleConfiguration: {
Rules: [{
"ID": "1",
"Status": "Enabled",
"Filter": {},
"Transition": {
"Days": "30",
"StorageClass": "STANDARD_IA"
}
}, {
"ID": "2",
"Status": "Enabled",
"Filter": {
"Prefix": "dir/"
},
"Transition": {
"Days": "90",
"StorageClass": "ARCHIVE"
}
}, {
"ID": "3",
"Status": "Enabled",
"Filter": {},
"Expiration": {
"Days": "180"
}
}, {
"ID": "4",
"Status": "Enabled",
"Filter": {},
"AbortIncompleteMultipartUpload": {
"DaysAfterInitiation": "30"
}
}],
}
}, function (err, data) {
logger.log('putBucketLifecycle:', err || data);
});
}
function getBucketLifecycle() {
cos.getBucketLifecycle({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketLifecycle:', err || data);
});
}
function deleteBucketLifecycle() {
cos.deleteBucketLifecycle({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('deleteBucketLifecycle:', err || data);
});
}
function putBucketVersioning() {
cos.putBucketVersioning({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
VersioningConfiguration: {
Status: "Enabled"
}
}, function (err, data) {
logger.log('putBucketVersioning:', err || data);
});
}
function getBucketVersioning() {
cos.getBucketVersioning({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketVersioning:', err || data);
});
}
function listObjectVersions() {
cos.listObjectVersions({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
// Prefix: "",
// Delimiter: '/'
}, function (err, data) {
logger.log('listObjectVersions:', err || JSON.stringify(data, null, ' '));
});
}
function putBucketReplication() {
var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
cos.putBucketReplication({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
ReplicationConfiguration: {
Role: "qcs::cam::uin/10001:uin/10001",
Rules: [{
ID: "1",
Status: "Enabled",
Prefix: "sync/",
Destination: {
Bucket: "qcs:id/0:cos:ap-chengdu:appid/" + AppId + ":backup",
// StorageClass: "Standard",
}
}]
}
}, function (err, data) {
logger.log('putBucketReplication:', err || data);
});
}
function getBucketReplication() {
cos.getBucketReplication({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketReplication:', err || data);
});
}
function deleteBucketReplication() {
cos.deleteBucketReplication({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('deleteBucketReplication:', err || data);
});
}
function putBucketWebsite() {
cos.putBucketWebsite({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
WebsiteConfiguration: {
IndexDocument: {
Suffix: "index.html" // 必选
},
RedirectAllRequestsTo: {
Protocol: "https"
},
// ErrorDocument: {
// Key: "error.html"
// },
// RoutingRules: [{
// Condition: {
// HttpErrorCodeReturnedEquals: "404"
// },
// Redirect: {
// Protocol: "https",
// ReplaceKeyWith: "404.html"
// }
// }, {
// Condition: {
// KeyPrefixEquals: "docs/"
// },
// Redirect: {
// Protocol: "https",
// ReplaceKeyPrefixWith: "documents/"
// }
// }, {
// Condition: {
// KeyPrefixEquals: "img/"
// },
// Redirect: {
// Protocol: "https",
// ReplaceKeyWith: "picture.jpg"
// }
// }]
}
}, function (err, data) {
logger.log('putBucketWebsite:', err || data);
});
}
function getBucketWebsite() {
cos.getBucketWebsite({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
},function(err, data){
logger.log('getBucketWebsite:', err || data);
});
}
function deleteBucketWebsite() {
cos.deleteBucketWebsite({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
},function(err, data){
logger.log('deleteBucketWebsite:', err || data);
});
}
function putBucketReferer() {
cos.putBucketReferer({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
RefererConfiguration: {
Status: 'Enabled',
RefererType: 'White-List',
DomainList: {
Domains: [
'*.qq.com',
'*.qcloud.com',
]
},
EmptyReferConfiguration: 'Allow',
}
}, function (err, data) {
logger.log('putBucketReferer:', err || data);
});
}
function getBucketReferer() {
cos.getBucketReferer({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
},function(err, data){
logger.log('getBucketReferer:', err || JSON.stringify(data, null, ' '));
});
}
function putBucketDomain() {
cos.putBucketDomain({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
DomainRule:[{
Status: "DISABLED",
Name: "www.testDomain1.com",
Type: "REST"
}, {
Status: "DISABLED",
Name: "www.testDomain2.com",
Type: "WEBSITE"
}]
},function(err, data){
logger.log('putBucketDomain:', err || data);
});
}
function getBucketDomain() {
cos.getBucketDomain({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
},function(err, data){
logger.log('getBucketDomain:', err || data);
});
}
function deleteBucketDomain() {
cos.deleteBucketDomain({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
},function(err, data){
logger.log('deleteBucketDomain:', err || data);
});
}
function putBucketLogging() {
var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
cos.putBucketLogging({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
BucketLoggingStatus: {
LoggingEnabled: {
TargetBucket: 'bucket-logging-' + AppId,
TargetPrefix: 'logging'
}
}
}, function (err, data) {
logger.log('putBucketLogging:', err || data);
});
}
function getBucketLogging() {
cos.getBucketLogging({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region
}, function (err, data) {
logger.log('getBucketLogging:', err || data);
});
}
function deleteBucketLogging() {
cos.putBucketLogging({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
BucketLoggingStatus: {}
}, function (err, data) {
logger.log('deleteBucketLogging:', err || data);
});
}
function putBucketInventory() {
var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
cos.putBucketInventory({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Id: 'inventory_test',
InventoryConfiguration: {
Id: 'inventory_test',
IsEnabled: 'true',
Destination: {
COSBucketDestination: {
Format: 'CSV',
AccountId: config.Uin,
Bucket: 'qcs::cos:ap-guangzhou::bucket-logging-' + AppId,
Prefix: 'inventory',
Encryption: {
SSECOS: ''
}
}
},
Schedule: {
Frequency: 'Daily'
},
Filter: {
Prefix: 'myPrefix'
},
IncludedObjectVersions: 'All',
OptionalFields: [
'Size',
'LastModifiedDate',
'ETag',
'StorageClass',
'IsMultipartUploaded',
'ReplicationStatus'
]
}
}, function (err, data) {
logger.log('putBucketInventory:', err || data);
});
}
function getBucketInventory() {
cos.getBucketInventory({
Bucket: config.Bucket,
Region: config.Region,
Id: 'inventory_test'
}, function(err, data) {
logger.log('getBucketInventory:', err || JSON.stringify(data));
});
}
function deleteBucketInventory() {
cos.deleteBucketInventory({
Bucket: config.Bucket,
Region: config.Region,
Id: 'inventory_test'
}, function(err, data) {
logger.log('deleteBucketInventory:', err || JSON.stringify(data));
});
}
function listBucketInventory() {
cos.listBucketInventory({
Bucket: config.Bucket,
Region: config.Region
}, function(err, data) {
logger.log('listBucketInventory:', err || JSON.stringify(data));
});
}
function putBucketEncryption() {
cos.putBucketEncryption({
Bucket: config.Bucket,
Region: config.Region,
ServerSideEncryptionConfiguration: {
Rule: [{
ApplySideEncryptionConfiguration: {
SSEAlgorithm: 'AES256',
},
}],
},
}, function(err, data) {
logger.log('putBucketEncryption:', err || JSON.stringify(data));
});
}
function getBucketEncryption() {
cos.getBucketEncryption({
Bucket: config.Bucket,
Region: config.Region
}, function(err, data) {
logger.log('getBucketEncryption:', err || JSON.stringify(data));
});
}
function deleteBucketEncryption() {
cos.deleteBucketEncryption({
Bucket: config.Bucket,
Region: config.Region
}, function(err, data) {
logger.log('deleteBucketEncryption:', err || JSON.stringify(data));
});
}
function putObject() {
// 创建测试文件
var filename = '1mb.zip';
var blob = util.createFile({size: 1024 * 1024 * 1});
// 调用方法
cos.putObject({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Key: filename, /* 必须 */
Body: blob,
onTaskReady: function (tid) {
TaskId = tid;
logger.log('onTaskReady', tid);
},
onTaskStart: function (info) {
logger.log('onTaskStart', info);
},
onProgress: function (progressData) {
logger.log(JSON.stringify(progressData));
},
Headers: {
// 万象持久化接口,上传时持久化
// 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
},
}, function (err, data) {
logger.log('putObject:', err || data);
});
}
// 简单上传 文件boby为base64
function putObject_base64ToBlob() {
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==';
var dataURLtoBlob = function (dataurl) {
var arr = dataurl.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
// 调用方法
cos.putObject({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Key: 'base64_file.png', /* 必须 */
Body: dataURLtoBlob(base64Url),
onTaskReady: function (tid) {
logger.log('onTaskReady', tid);
},
onTaskStart: function (info) {
logger.log('onTaskStart', info);
},
onProgress: function (progressData) {
logger.log(JSON.stringify(progressData));
},
Headers: {
// 万象持久化接口,上传时持久化
// 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
},
}, function (err, data) {
logger.log('putObject:', err || data);
});
}
function putObjectCopy() {
cos.putObjectCopy({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Key: '1mb.copy.zip',
CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + camSafeUrlEncode('1mb.zip').replace(/%2F/g, '/'), // Bucket 格式:test-1250000000
}, function (err, data) {
logger.log('putObjectCopy:', err || data);
});
}
function getObject() {
cos.getObject({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Key: '1mb.zip',
onProgress: function (progressData) {
logger.log(JSON.stringify(progressData));
}
}, function (err, data) {
logger.log('getObject:', err || data);
});
}
function headObject() {
cos.headObject({
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Key: '1mb.zip'
}, function (err, data) {
logger.log('headObject:', err || data);
});
}
function putObjectAcl() {
cos.putObjectAcl({
Bucket: config.Bucket, // Bucket 格式:test-1250000000