*, and ExposeHeaders should include ETag, Content-Length, and other header fields required by JavaScript, as shown in the figure below. For operation details, see the Set Cross-Origin Access documentation.
<!--src is a local path; adjust according to your project directory structure--><script src="../dist/cos-js-sdk-v5.min.js"></script>
npm i cos-js-sdk-v5 --save. This supports Webpack bundling scenarios. You can import it as a module using npm, as shown in the following code:const COS = require('cos-js-sdk-v5');// Orimport COS from 'cos-js-sdk-v5';
import COS from 'cos-js-sdk-v5';// console.log(COS.version); The sdk version must be at least 1.8.3.const cos = new COS({SecretId: 'your_tmpSecretId', // Temporary SecretId issued by the sts serviceSecretKey: 'your_tmpSecretKey', // Temporary SecretKey issued by the sts serviceSecurityToken: 'your_sessionToken', // Temporary SessionToken issued by the sts serviceStartTime: 1720770679403, // It is recommended to pass the server-side time to avoid signature errors caused by inaccurate client timeExpiredTime: 1720771991367, // Expiration time of the temporary secret key});
import COS from 'cos-js-sdk-v5';const cos = new COS({getAuthorization: async function (options, callback) {const data = await fetchSts('xxxx'); // The logic for obtaining temporary credentials needs to be implemented by yourself.callback({TmpSecretId: data.credentials.tmpSecretId,TmpSecretKey: data.credentials.tmpSecretKey,SecurityToken: data.credentials.sessionToken,// It is recommended to return the server time as the start time of the signature to avoid signature errors caused by excessive deviation in the client's local time.StartTime: data.startTime, // Timestamp in seconds, such as 1580000000ExpiredTime: data.expiredTime, // Timestamp in seconds, such as 1580000000ScopeLimit: true, // Fine-grained permission control needs to be set to true, which restricts the key to be reused only for the same request.});}});
import COS from 'cos-js-sdk-v5';const cos = new COS({// For other configuration items, refer to the Configuration Items for Initialization below.// required parameters for getAuthorizationgetAuthorization: function (options, callback) {// It is not called during initialization; it will only be entered when cos methods are called (such as cos.putObject)// Asynchronously obtain temporary credentials// Server-side JS example: https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/// For server-side implementations in other languages, refer to COS STS SDK: https://github.com/tencentyun/qcloud-cos-sts-sdk.// For detailed STS documentation, see: https://www.tencentcloud.com/document/product/436/14048.const stsUrl = 'http://example.com/server/sts'; // Replace stsUrl with your own backend service.fetch(stsUrl).then(response => response.json()).then(data => {if (!data || !data.credentials) {return console.error('credentials invalid:\\n' + JSON.stringify(data, null, 2))}// Check the credentials format.const { credentials } = data;console.log(credentials);callback({TmpSecretId: credentials.tmpSecretId,TmpSecretKey: credentials.tmpSecretKey,SecurityToken: credentials.sessionToken,// It is recommended to return the server time as the start time of the signature to avoid signature errors caused by significant deviation in the client's local time.StartTime: data.startTime, // Timestamp in seconds, such as 1580000000ExpiredTime: data.expiredTime, // Timestamp in seconds, such as 1580000000ScopeLimit: true, // Fine-grained permission control needs to be set to true, which restricts the key to be reused only for the same request.});}).catch(error => {console.error('Failed to obtain temporary credentials', error);});}});export default cos;
import cos from 'utils/cos';let taskId;// Upload file, file is the selected file.async function upload(file) {try {const data = await cos.uploadFile({Bucket: 'examplebucket-1250000000', // Replace with your own bucket name. Required.Region: 'COS_REGION', // The region where the bucket is located. Required.Key: '1.jpg', // The object key stored in the bucket (such as 1.jpg and a/b/test.txt). Required.Body: file, // Upload file object.SliceSize: 1024 * 1024 * 5, // Threshold for triggering multipart upload. Files larger than 5MB use multipart upload; files smaller than 5MB use simple upload. Can be customized. Optional.onProgress: function(progressData) {console.log('Upload progress:', progressData);},onTaskReady: function(id) { // OptionaltaskId = id;},});console.log('Upload succeeded', data);} catch (e) {console.error('Upload failed', e);}}// Listen to the upload queue.cos.on('update-list', data => {console.log(data);});// Pause the upload task.cos.pauseTask(taskId);// Restart the upload task.cos.restartTask(taskId);// Cancel the upload task.cos.cancelTask(taskId)
import COS from 'cos-js-sdk-v5';// For SECRETID and SECRETKEY, please log in to https://console.tencentcloud.com/cam/capi to view and manage them.const cos = new COS({SecretId: process.env.SecretId, // It is recommended to obtain via environment variables; User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1SecretKey: process.env.SecretKey, // It is recommended to obtain via environment variables; User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1});
Parameter Name | Parameter Description | Type | Required or Not |
SecretId | The user's SecretId. When passing a permanent key, it is recommended to use it only during frontend debugging to avoid key exposure. | String | No |
SecretKey | The user's SecretKey. When a permanent key is passed, it is recommended to use it only during frontend debugging to avoid key exposure. | String | No |
SecurityToken | The sessionToken of the obtained temporary keys (supported since version v1.8.3). When temporary keys are passed for SecretId and SecretKey, SecurityToken is required. | String | No |
StartTime | The start timestamp of the obtained temporary keys' validity period (supported since version v1.8.3), unit: seconds. When temporary keys are passed for SecretId and SecretKey, it is recommended to pass StartTime. | Number | No |
ExpiredTime | The expiration timestamp of the obtained temporary keys (supported since version v1.8.3), unit: seconds. When temporary keys are passed for SecretId and SecretKey, it is recommended to pass ExpiredTime. | Number | No |
FileParallelLimit | The concurrency of file uploads under the same instance, default value is 3. | Number | No |
ChunkParallelLimit | The concurrency of parts per uploaded file, default value is 3. | Number | No |
ChunkRetryTimes | The number of retries on error during multipart upload and multipart copy, default value is 2 (first attempt plus two retries, totaling three requests). | Number | No |
ChunkSize | The size in bytes of each part during multipart upload, default value is 1048576 (1MB). | Number | No |
SliceSize | When uploadFiles is used for batch upload, files larger than this size will use multipart upload; otherwise, simple upload will be invoked. Unit: Byte, default value is 1048576 (1MB). | Number | No |
CopyChunkParallelLimit | The concurrency of multipart copy operations performed during multipart upload, default value is 20. | Number | No |
CopyChunkSize | The size in bytes of each part when the sliceCopyFile is used for multipart copy, default value is 10485760 (10MB). | Number | No |
CopySliceSize | When sliceCopyFile is used for multipart copy, files larger than this size will use multipart copy; otherwise, simple copy will be invoked. Default value is 10485760 (10MB). | Number | No |
ProgressInterval | The callback frequency of the onProgress callback method for upload progress, unit: ms, default value is 1000. | Number | No |
Protocol | The protocol used when requests are sent, options include https: and http:. By default, it uses http: if the current page is http:; otherwise, it uses https:. | String | No |
Domain | When calling APIs to operate on buckets and objects, you can customize the request domain name. Templates can be used, such as "{Bucket}.cos.{Region}.myqcloud.com", where the Bucket and Region in the parameters passed in will be replaced when the API is called. | String | No |
UploadQueueSize | The maximum length of the upload queue. Tasks that exceed this limit will be cleared if their status is not waiting, checking, or uploading. Default value is 10000. | Number | No |
UploadCheckContentMd5 | When uploading files, verify the Content-MD5, default is false. If the Content-MD5 is enabled, the MD5 of the file content will be calculated during upload, which may take longer for large files. | Boolean | No |
UploadAddMetaMd5 | Verify Content-MD5 when files are uploaded, default is false. When the Content-MD5 verification is enabled, the x-cos-meta-md5 header will be added to upload requests. | Boolean | No |
getAuthorization | The callback method to obtain the signature. This parameter is required if SecretId and SecretKey are not provided. Note: This callback method is passed in when the instance is initialized and will be executed to obtain the signature only when using the instance to call an interface. | Function | No |
Timeout | Timeout in milliseconds, default is 0, meaning no timeout. | Number | No |
UseAccelerate | Whether to enable the domain name for Global Acceleration, default is false. If set to true, the bucket must have the feature for Global Acceleration enabled. For details, see Enabling Global Acceleration. | Boolean | No |
getAuthorization: function(options, callback) { ... }
Parameter Name | Parameter Description | Type |
options | Parameters required for obtaining a temporary key. | Object |
- Bucket | The name of the bucket, in the format BucketName-APPID. The bucket name entered here must be in this format. | String |
- Region | String | |
callback | Callback method after a temporary key is obtained. | Function |
Property Name | Parameter Description | Type | Required or Not |
TmpSecretId | tmpSecretId of the obtained temporary key. | String | Yes |
TmpSecretKey | tmpSecretKey of the obtained temporary key. | String | Yes |
SecurityToken | The sessionToken of the obtained temporary key, corresponding to the x-cos-security-token field in the header. | String | Yes |
StartTime | The start time for obtaining the key, that is, the timestamp at the moment of acquisition, in seconds (startTime, such as: 1580000000). This parameter specifies the start time for signature generation to prevent signature expiration issues caused by frontend time deviation. | String | No |
ExpiredTime | expiredTime of the obtained temporary key, the expiration timestamp in seconds, such as: 1580000900. | String | Yes |
// For a complete demo, refer to: https://github.com/tencentyun/cos-js-sdk-v5/blob/master/demo/index.html.const Beacon = require('./lib/beacon_mp.min');new COS({...BeaconReporter: Beacon,})
// Here, the initialization process and upload parameters are omitted.var cos = new COS({ ... });cos.uploadFile({ ... }, function(err, data) {if (err) {console.log('Upload error', err);} else {console.log('Upload succeeded', data);}});
// Here, the initialization process and upload parameters are omitted.var cos = new COS({ ... });cos.uploadFile({ ... }).then(data => {console.log('Upload succeeded', data);}).catch(err => {console.log('Upload error', err);});
async function upload() {// Here, the initialization process and upload parameters are omitted.var cos = new COS({ ... });try {var data = await cos.uploadFile({ ... });return { err: null, data: data }} catch (err) {return { err: err, data: null };}}// You can synchronously obtain the return value of the request. This is an example, and the actual returned data format can be customized.var uploadResult = await upload();if (uploadResult.err) {console.log('Upload error', uploadResult.err);} else {console.log('Upload succeeded', uploadResult.data);}// JavaScript async and await (Note that browser compatibility should be considered when they are used.)
/* example of a Vue project *//* Create a cos.js file and export the cos instance. */import COS from 'cos-js-sdk-v5'; // SDK installed via npmconst cos = new COS({SecretId: 'your SecretId',SecretKey: 'your SecretKey',});export default cos;/* In a single page: page.vue */<template><div><button @click="getBucketFiles">Get files in directory a</button><div v-if="fileList.length"><h4>File list in directory a:</h4><ul><li v-for="(file, i) in fileList" :key="i">{{ file.Key }}</li></ul></div><p v-if="error" style="color: red;">{{ error }}</p></div></template><script>import cos from '@/utils/cos';export default {data() {return {fileList: [],error: ''};},methods: {getBucketFiles() {cos.getBucket({Bucket: 'examplebucket-1250000000', // Your bucketRegion: 'COS_REGION', // Your region (such as ap-guangzhou)Prefix: 'a/' // Only query files in the a/ directory}, (err, data) => {if (err) {this.error = 'Query failed: ' + err.Message;this.fileList = [];} else {this.error = '';this.fileList = data.Contents || []; // Display file paths (Key)}});}}};</script>
simple upload of objects and multipart upload permissions. See Authorization Guide.<template><div><input type="file" @change="handleUpload" /></div></template><script>// Directly import cos-js-sdk-v5 (via npm installation).import COS from 'cos-js-sdk-v5';export default {methods: {handleUpload(e) {const file = e.target.files[0];if (!file) return;// Initialize COS instance directly within the componentconst cos = new COS({SecretId: 'your SecretId', // Replace with actual SecretIdSecretKey: 'your SecretKey' // Replace with actual SecretKey.});// Call the upload methodcos.uploadFile({Bucket: 'examplebucket-1250000000',Region: 'ap-guangzhou',Key: `upload/${Date.now()}-${file.name}`,Body: file,SliceSize: 1024 * 1024 * 5}, (err, data) => {err ? console.error('Upload failed', err) : console.log('Upload succeeded', data);e.target.value = ''; // Clear selection.});}}};</script>
<template><div><input type="text" v-model="fileKey" placeholder="Enter file Key (e.g., a/1.jpg)" /><button @click="getDownloadUrl">Download</button></div></template><script>import COS from 'cos-js-sdk-v5';export default {data() {return {fileKey: '',cos: new COS({SecretId: 'your SecretId',SecretKey: 'your SecretKey'})};},methods: {getDownloadUrl() {if (!this.fileKey) return;this.cos.getObjectUrl({Bucket: 'examplebucket-1250000000',Region: 'COS_REGION',Key: this.fileKey}, (err, data) => {if (err) return console.error(err);// Build a link for forced downloadconst downloadUrl = data.Url + (data.Url.includes('?') ? '&' : '?') + 'response-content-disposition=attachment';window.open(downloadUrl);});}}};</script>
<template><div><input type="text" v-model="fileKey" placeholder="Enter file Key to delete (e.g., a/1.jpg)" /><button @click="deleteFile">Delete File</button></div></template><script>import COS from 'cos-js-sdk-v5';export default {data() {return {fileKey: '',cos: new COS({SecretId: 'your SecretId',SecretKey: 'your SecretKey'})};},methods: {deleteFile() {if (!this.fileKey.trim()) return;this.cos.deleteObject({Bucket: 'examplebucket-1250000000',Region: 'COS_REGION',Key: this.fileKey.trim()}, (err, data) => {if (err) {console.error('Deletion failed', err);} else {console.log('Deletion successful', data);this.fileKey = ''; // Clear input.}});}}};</script>
Feedback