This topic describes how to add signatures to requests by using Node.js on application servers, configure upload callback, and then use form upload to upload data to Object Storage Service (OSS).

Prerequisites

  • The domain name of the application server can be accessed over the Internet.
  • Node.js 8.0 or later is installed on the application server. You can run the node -v command to obtain the Node.js version used on the application server.
  • The browser used by the client must support HTML4, HTML5, Flash, and Silverlight.

Step 1: Configure the app server

  1. Download the application server source code.
  2. Ubuntu 16.04 is used in the example. Decompress the source code to the /home/aliyun/aliyun-oss-appserver-node.js directory.
  3. Run the npm install command in the root directory of your project.
  4. Find the app.js source code file in the root directory of your project and modify the following snippet:
    const config = {
      // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
      accessKeyId: 'yourAccessKeyId', 
      accessKeySecret: 'yourAccessKeySecret',
      // Specify the bucket name. 
      bucket: 'yourBucket',
      // Set the URL of the application server to which an upload callback request is sent. This URL is used to communicate between the application server and OSS. After an object is uploaded, OSS uses the URL to send information about the object to the application server. For example, you can set callbackUrl to https://oss-demo.aliyuncs.com:23450. 
      callbackUrl: 'yourCallBackUrl',
      // Configure the parameter if you want to specify a prefix for the objects to upload. Otherwise, you can leave the parameter empty. 
      dir: 'yourPrefix'
    }

Step 2: Configure the client

  1. Download the client source code.
  2. Decompress the downloaded package. Decompress the package to a directory. The D:\aliyun\aliyun-oss-appserver-js directory is used in this example.
  3. Go to the directory. Open the upload.js file. Find the following code:
    // serverUrl specifies the URL of the application server that users use to obtain information such as the signature and upload policy. Replace the IP address and port number with your actual information. 
    serverUrl = 'http://88.88.88.88:8888'
  4. Set severUrl to the URL of the application server. For example, you can set severUrl to serverUrl = 'https://oss-demo.aliyuncs.com:23450' so that the client can use the URL to obtain required information such as the signature and upload policy.

Step 3: Configure CORS

When you use form upload to upload data from the client to OSS, the client sends a request that contains the Origin header to OSS by using the browser. Then, OSS verifies the request that contains the Origin header against the cross-origin resource sharing (CORS) rules that you configure for a specific bucket. Therefore, you must configure CORS rules for the bucket before users can use the POST method to upload data to the bucket.

  1. Log on to the OSS console.
  2. Click Buckets, and then click the name of the target bucket.
  3. Choose Access Control > Cross-Origin Resource Sharing (CORS). In the Cross-Origin Resource Sharing (CORS) section, click Configure.
  4. Click Create Rule and configure the parameters showed in the following figure.
    Note To ensure data security, we recommend that you specify the actual domain name from which you want OSS to allow requests in Sources. For more information about how to configure the parameters, see Configure CORS rules.

Step 4: Send an upload callback request

  1. In the root directory of the application server, run the npm run server command to start the application server.
  2. On the PC client, open the index.html file in the directory of the client source code.
    Notice Internet Explorer below IE 10 may be incompatible with the index.html file. You must troubleshoot the errors yourself if you use browsers below IE 10.
  3. Click Select File. Select the file of a specified type. Click Upload.
    After the object is uploaded, the content returned by the application server is displayed.

Analysis of the application server source code

The application server source code contains a complete sample code for adding signatures, uploading objects to OSS, and configuring upload callback. The following code provides only the core code snippet. For more information about how to implement features, download application server source code and view the details.

  • Add signatures to requests and upload objects to OSS
    The following snippet provides an example on how to obtain parameter values used for signature and the URL of the application server:
    app.get("/", async (req, res) => {
      const client = new OSS(config);
    
      const date = new Date();
      date.setDate(date.getDate() + 1);
      const policy = {
        expiration: date.toISOString(), // Set the UNIX timestamp that is in seconds since the UTC time January 1, 1970 to identify the timeout period of the upload request. 
        conditions: [
          ["content-length-range", 0, 1048576000] // Set the size limit for the object to upload.       
        ],
      };
    
      // Configure the CORS rules. 
      res.set({
        "Access-Control-Allow-Origin": req.headers.origin || "*",
        "Access-Control-Allow-Methods": "PUT,POST,GET",
      });
    
      // Use the SDK to obtain the signature. 
      const formData = await client.calculatePostSignature(policy);
      // Specify the endpoint of the bucket over the Internet. 
      const host = `http://${config.bucket}.${
        (await client.getBucketLocation()).location
      }.aliyuncs.com`.toString();
      // Configure upload callback. 
      const callback = {
        callbackUrl: config.callbackUrl,// Set the URL of the application server used to send upload callback requests. Example: http://oss-demo.aliyuncs.com:23450. 
        callbackBody:// Specify the content that you want the callback request to contain such as the ETag and the mimeType of the uploaded object. 
          "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}",
        callbackBodyType: "application/x-www-form-urlencoded",// Set the content type of the callback information.     
      };
    
      // Specify the required parameters contained in the response. 
      const params = {
        expire: moment().add(1, "days").unix().toString(),
        policy: formData.policy, // The policy obtained from OSS. 
        signature: formData.Signature, // The signature obtained from OSS. 
        accessid: formData.OSSAccessKeyId,// The AccessKey ID obtained from OSS. 
        host, // The format is https://bucketname.endpoint. Example: https://bucket-name.oss-cn-hangzhou.aliyuncs.com. 
        callback: Buffer.from(JSON.stringify(callback)).toString("base64"),// The Base64-encoded JSON by using Buffer.from. 
        dir: config.dir,// The obtained prefix for the uploaded object. 
      };
    
      res.json(params);
    });
  • Upload callback

    The following snippet provides an example on how to configure the POST response returned by the application server to the callback request sent by OSS:

    // Listen the POST requests in the /result path. 
    app.post("/result", (req, res) => {
      // Decode the address of the OSS public key by using Base64. 
      const pubKeyAddr = Buffer.from(
        req.headers["x-oss-pub-key-url"],
        "base64"
      ).toString("ascii");
      // Determine whether x-oss-pub-key-url in the request header comes from OSS. 
      if (
        !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/") &&
        !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")
      ) {
        System.out.println("pub key addr must be oss addrss");
        // If not, return "verify not ok", which indicates that the upload callback fails. 
        res.json({ Status: "verify not ok" });
      }
      // If x-oss-pub-key-url comes from OSS, this indicates that the upload callback succeeds. 
      res.json({ Status: "Ok" });
    });

    For more information about upload callback, see Callback.