Common questions and solutions for the OSS Browser.js SDK.
How do I call STS?
Browsers are untrusted environments. Storing your AccessKey ID and AccessKey Secret directly in the browser poses a high security risk. Use Security Token Service (STS) to call OSS API operations from a browser.
After you obtain an STS token, initialize the SDK as follows.
<script type="text/javascript">
$.ajax("http://your_sts_server/",{method: 'GET'},function (err, result) {
let client = new OSS({
authorizationV4: true,
accessKeyId: result.AccessKeyId,
accessKeySecret: result.AccessKeySecret,
stsToken: result.SecurityToken,
region: 'yourRegion',
bucket: 'yourBucketName'
});
});
</script>
How do I enable HTTPS access?
Set secure:true during SDK initialization. For more information, see Initialization (Browser.js SDK).
How do I resolve cross-domain issues in a browser?
Configure cross-origin resource sharing (CORS) rules for the bucket before using the SDK in a browser. For more information, see Preparations.
How do I set user-defined metadata, MIME types, and request headers for an uploaded file?
For more information, see Simple upload (Browser.js SDK).
How does resumable upload work in a browser?
Save the checkpoint to the browser's local storage and pass it in the next call to resume the upload. For more information, see Resumable upload (Browser.js SDK).
How do I upload a file to a specific folder?
Specify a prefix for the object name to upload a file to a specific folder.
let OSS = require('ali-oss')
let client = new OSS({
authorizationV4: true,
region: 'yourRegion',
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
bucket: 'yourBucketName'
});
client.multipartUpload('base-dir/' +'object-key', 'local-file', {
progress: async function (p) {
console.log('Progress: ' + p);
}
});
console.log(result);
}).catch((err) => {
console.log(err);
});
How do I upload a Base64-encoded image?
Convert the Base64 data into an image, then call an OSS upload operation. For more information, see the GitHub example.
/**
* Converts Base64 to a file.
* @param dataurl The Base64 content.
* @param filename Set a meaningful suffix. You can also set the MIME type in the options.
* @returns {File|*}
*/
const dataURLtoFile = function dataURLtoFile(dataurl, filename) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });// if env support File, also can use this: return new File([u8arr], filename, { type: mime });
};
// The client is an OSS client instance.
const uploadBase64Img = function uploadBase64Img(client) {
// The Base64 content.
const base64Content = 'data:image:****';
const filename = 'img.png';
const imgfile = dataURLtoFile(base64Content, filename);
// The key is the object key for the upload. The imgFile is the image returned after being processed by dataURLtoFile.
client.multipartUpload(key, imgfile).then((res) => {
console.log('upload success: %j', res);
}).catch((err) => {
console.error(err);
});
};
How do I limit the size of an uploaded file?
In a browser, retrieve the file size in bytes from document.getElementById("file").files[0].size. For more information about POST requests, see Upload data to OSS from a browser.
How do I get the upload progress?
Use multipart upload to track the upload progress. For more information, see Multipart upload (Browser.js SDK).
How do I get the download progress?
The Browser.js SDK does not support tracking download progress. Call the signatureUrl method to generate a download URL instead. For more information, see References.
How do I get the signed URL for an object?
Call the signatureUrl method to generate a signed download URL. For more information, see Preview or download files (Browser.js SDK).
How do I use an SDK-generated signed URL to upload a resource?
Signed URLs grant third-party access for uploading and downloading resources. The SDK provides the signatureUrl method to generate a signed URL. For an example, see Example of uploading a resource using a signed URL.
How do I use a form to upload a resource to an OSS server?
For more information, see Upload data to OSS from a browser.
How do I run the example project?
Navigate to the ali-oss/example directory and run npm run start.
How do I add an upload callback?
const uploadFile = function uploadFile(client) {
if (!uploadFileClient || Object.keys(uploadFileClient).length === 0) {
uploadFileClient = client;
}
const file = document.getElementById('file').files[0];
const key = document.getElementById('object-key-file').value.trim() || 'object';
console.log(`${file.name} => ${key}`);
const options = {
progress,
partSize: 500 * 1024,
timeout:60000,
meta: {
year: 2017,
people: 'test',
},
callback: {
// The position where the upload callback is added.
url: 'https://example.aliyundoc.com/v2/sync',
/* host: 'oss-cn-shenzhen.aliyuncs.com', */
/* eslint no-template-curly-in-string: [0] */
body: 'bucket=${bucket}&object=${object}&var1=${x:var1}',
contentType: 'application/x-www-form-urlencoded',
customValue: {
var1: 'value1',
var2: 'value2',
},
},
For more information about upload callbacks, see How it works.
Does the browser support browsing files by chunk?
No. The Browser.js SDK does not support chunked file browsing.
How do I collect logs with the OSS JS SDK?
For more information, see GitHub.