edit-icon download-icon

Quick start: browser

Last Updated: Jun 26, 2018

This document describes how to quickly access the OSS service in the BrowserJS-SDK, including uploading/downloading files and viewing file lists.

Note: Since the Alibaba Cloud account AccessKey gives you permission to access all APIs, we recommend that you not use the AK that can cause configuration leak by following the Alibaba Cloud Security Best Practices. Therefore, you must create and use STS (temporary account permission) to authorize the client.

For demo project, see example.

Bucket settings

The CORS settings of the bucket must be enabled to access OSS directly in a browser:

  • Set allowed origins to *
  • Set allowed methods to PUT, GET, POST, DELETE, and HEAD
  • Set allowed headers to *
  • Set expose headers to ETag x-oss-request-id

Note: Set the CORS rule as the first option.

cors

Use the SDK

Currently, browsers do not support direct bucket-related operations (for example, list buckets, and get/set bucket logging/referer/website/cors), but support object-related operations (for example, upload/download files, and view file lists).

Include the SDK

First, include the following tags in the <head> of the HTML file:

  1. <script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-x.x.x.min.js"></script>

For more introduction methods, see Installation.

Create a client using new OSS.Wapper(). OSS.Wrapper provides an asynchronous API similar to the callback method to process the returned results in .then() and process errors in .catch().

Build an STS Server and obtain temporary authorization information from the client

  1. Activate the STS service for your account. If the service has been activated, you can skip this step. To activate the STS service, see STS Activation. For more information on how to configure OSS authorization policy, see RAM and STS authorization policy configuration.

  2. Apply the exclusive STS signature service through the STS SDK or API. To help you quickly get started with the STS service, we provide demo programs in multiple languages:

  3. Initiate requests to the STS service built in the frontend (browser) to obtain the STS temporary authorization information.

    1. <script type="text/javascript">
    2. OSS.urllib.request("http://your_sts_server/",
    3. {method: 'GET'},
    4. function (err, response) {
    5. if (err) {
    6. return alert(err);
    7. }
    8. try {
    9. result = JSON.parse(response);
    10. } catch (e) {
    11. errmsg = 'parse sts response info error: ' + e.message;
    12. return alert(errmsg);
    13. }
    14. // console.log(result)
    15. })
    16. </script>

View file lists

  1. <script type="text/javascript">
  2. OSS.urllib.request("http://your_sts_server/",
  3. {method: 'GET'},
  4. function (err, response) {
  5. if (err) {
  6. return alert(err);
  7. }
  8. try {
  9. result = JSON.parse(response);
  10. } catch (e) {
  11. return alert('parse sts response info error: ' + e.message);
  12. }
  13. var client = new OSS.Wrapper({
  14. accessKeyId: result.AccessKeyId,
  15. accessKeySecret: result.AccessKeySecret,
  16. stsToken: result.SecurityToken,
  17. endpoint: '<oss endpoint>',
  18. bucket: '<Your bucket name>'
  19. });
  20. client.list({
  21. 'max-keys': 10
  22. }).then(function (result) {
  23. console.log(result);
  24. }).catch(function (err) {
  25. console.log(err);
  26. });
  27. });
  28. </script>

The parameter region refers to the region used when you applied for OSS, such as oss-cn-hangzhou. The completeregion list can be viewed in OSS Nodes.

Open the HTML file in the browser, and open the Chrome Developer Console to view the list filesresult.

list

Note: A browser is an untrusted environment. An extremely high risk occurs if you store the AccessKeyID and AccessKeySecret in a browser. We recommend that you only use plaintext settings for testing purposes. STS authentication mode or self-signed mode is recommended for business applications. For more information, see Resource Access Management and Direct Transfer on a Mobile Device.

Upload files

We use the multipartUpload API to upload files. For more information about multipartUpload, see Multipart upload.

  1. <body>
  2. <input type="file" id="file" />
  3. <script type="text/javascript">
  4. document.getElementById('file').addEventListener('change', function (e) {
  5. var file = e.target.files[0];
  6. var storeAs = 'upload-file';
  7. console.log(file.name + ' => ' + storeAs);
  8. OSS.urllib.request("http://your_sts_server/",
  9. {method: 'GET'},
  10. function (err, response) {
  11. if (err) {
  12. return alert(err);
  13. }
  14. try {
  15. result = JSON.parse(response);
  16. } catch (e) {
  17. return alert('parse sts response info error: ' + e.message);
  18. }
  19. var client = new OSS.Wrapper({
  20. accessKeyId: result.AccessKeyId,
  21. accessKeySecret: result.AccessKeySecret,
  22. stsToken: result.SecurityToken,
  23. endpoint: '<oss endpoint>',
  24. bucket: '<Your bucket name>'
  25. });
  26. //storeAs indicates the uploaded object name and file indicates the uploaded file
  27. client.multipartUpload(storeAs, file).then(function (result) {
  28. console.log(result);
  29. }).catch(function (err) {
  30. console.log(err);
  31. });
  32. });
  33. });
  34. </script>
  35. </body>

upload

Download files

You cannot directly operate on files in the browser. Therefore, the download link of a file is generated using the signed URL method, andyou can download the file by clicking the link.

  1. <body>
  2. <input type="button" id="download" value="Download" />
  3. <script type="text/javascript">
  4. document.getElementById('download').addEventListener('click', function (e) {
  5. var objectKey = 'test/download_file';
  6. var saveAs = 'download_file';
  7. console.log(objectKey + ' => ' + saveAs);
  8. OSS.urllib.request("http://your_sts_server/",
  9. {method: 'GET'},
  10. function (err, response) {
  11. if (err) {
  12. return alert(err);
  13. }
  14. try {
  15. result = JSON.parse(response);
  16. } catch (e) {
  17. return alert('parse sts response info error: ' + e.message);
  18. }
  19. var client = new OSS.Wrapper({
  20. accessKeyId: result.AccessKeyId,
  21. accessKeySecret: result.AccessKeySecret,
  22. stsToken: result.SecurityToken,
  23. endpoint: '<oss endpoint>',
  24. bucket: '<Your bucket name>'
  25. });
  26. var result = client.signatureUrl(objectKey, {
  27. expires: 3600,
  28. response: {
  29. 'content-disposition': 'attachment; filename="' + saveAs + '"'
  30. }
  31. });
  32. console.log(result);
  33. window.location = result;
  34. });
  35. });
  36. </script>
  37. </body>

download_with_sts

Thank you! We've received your feedback.