To perform file uploads using the CSP pattern, initialize the COS instance with a getAuthorization function that fetches signatures from your backend, then use sliceUploadFile for the upload process.
Steps:
- Create an HTML file with a file input.
- Include the
cos-js-sdk-v5.min.js script. - Configure the
Bucket and Region. - Implement
getAuthorization to call your backend endpoint (e.g., a PHP or Node.js script) that returns the signature JSON. - Use
cos.sliceUploadFile to handle the upload (this method supports chunked uploading).
<input id="file-selector" type="file">
<script src="dist/cos-js-sdk-v5.min.js"></script>
<script>
var Bucket = 'test-1250000000';
var Region = 'ap-guangzhou';
// Initialize instance
var cos = new COS({
CompatibilityMode: true,
ServiceDomain: 'http://cos.default.xxx.com', // Replace with getService domain
Domain: 'http://{Bucket}.cos.{Region}.xxx.com', // Replace with API domain template
getAuthorization: function (options, callback) {
// Request signature from your backend
var url = './auth-json.php?method=' + options.Method + '&path=' + encodeURIComponent('/' + options.Key);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
callback(e.target.responseText);
};
xhr.send();
},
});
// Listen for file selection
document.getElementById('file-selector').onchange = function () {
var file = this.files[0];
if (!file) return;
// Chunked upload file
cos.sliceUploadFile({
Bucket: Bucket,
Region: Region,
Key: file.name,
Body: file,
}, function (err, data) {
console.log(err, data);
});
};
</script>