All Products
Search
Document Center

Object Storage Service:Java

Last Updated:Feb 27, 2024

This topic describes how to calculate signatures in Java on the application server, configure upload callbacks, 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.

  • Java 1.6 or later is installed on the application server. To view the Java version, run the java -version command.

  • JavaScript is supported by the browser on your computer.

Step 1: Configure the application server

  1. Download the application server source code package in Java.

  2. In this example, Ubuntu 16.04 is used. Extract the downloaded package to the /home/aliyun/aliyun-oss-appserver-java directory.

  3. Go to the directory, open the CallbackServer.java source code file, and then modify the source code file based on your business requirements. The following sample code provides an example on how to modify the source code file:

    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
    // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
    String endpoint = "oss-cn-hangzhou.aliyuncs.com"; 
    // Specify the name of the bucket. Example: examplebucket. 
    String bucket = "examplebucket"; 
    // Specify the name of the host in the https://bucketname.endpoint format.                    
    String host = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com"; 
    // Specify the URL of the application server to which an upload callback request is sent. The URL must be a public domain name. This URL is used for communication between the application server and OSS. After you upload an object, OSS uses the URL to send upload information to the application server. 
    String callbackUrl = "https://192.168.0.0:8888";
    // Specify the prefix of the object that you want to upload. You can leave this parameter empty. If you do not specify this parameter, the object is uploaded to the root directory of the bucket. 
    String dir = "exampledir/"; 

Step 2: Configure the client

  1. Download the client source code package.

  2. Extract the package to a directory. In this example, the D:\aliyun\aliyun-oss-appserver-js directory is used.

  3. Go to the directory, open the upload.js file, and then find the following code:

    // serverUrl specifies the URL of the application server that returns information such as the signature and upload policies. Replace the value of serverUrl with the actual IP address and port number of the application server. 
    serverUrl = 'http://192.0.2.0:8888'
  4. Set serverUrl to the URL of the application server that returns information such as the signature and upload policies to the client. In this example, serverUrl is set to https://192.168.0.0:8888.

Step 3: Configure CORS

When you use form upload to upload data from the client to OSS, a request that contains the Origin header is sent from the browser to OSS. Then, OSS checks whether the request that contains the Origin header matches the cross-origin resource sharing (CORS) rules that you configured for the bucket. Therefore, you must configure CORS rules for the bucket before users use the POST method to upload data to the bucket.

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Content Security > CORS (Cross-Origin Resource Sharing).

  4. On the CORS page, click Create Rule and configure the parameters in the Create Rule panel, as shown in the following figure.

    Note

    To ensure data security, we recommend that you specify the domain name from which you want OSS to allow requests in the Source field. For more information about how to configure the parameters, see Configure CORS.

Step 4: Send an upload callback request

  1. Start the application server.

    In the /home/aliyun/aliyun-oss-appserver-java directory, run the mvn package command to compile and package the code. Then, run the java -jar target/appservermaven-1.0.0.jar 1234 command to start the application server.

    Note

    Replace the IP address and port number with the IP address and port number of the application server that you configured.

    You also can use an integrated development environment (IDE), such as Eclipse or IntelliJ IDEA, to export the JAR package to your on-premises device and copy the JAR package to the application server. Then, run the JAR package to start the application server.

  2. Start the client.

    1. On the client that is installed on your on-premises device, open the index.html file in the directory of the client source code.

      Important The index.html file may be incompatible with Internet Explorer 10 or earlier. If you encounter any problems when you use Internet Explorer 10 or earlier, you must perform debugging.
    2. Click Select File, select a file of the specified type, and then click Upload.

      After you upload the file, the content that is returned by the application server is displayed.

Analysis of application server source code

The source code of the application server contains the following complete sample code for signature-based uploads and upload callbacks:

  • Signature-based uploads

    During signature-based uploads, the application server responds to the GET requests that are sent from a client. Sample code:

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
           // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
           EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
           // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
           String endpoint = "oss-cn-hangzhou.aliyuncs.com"; 
           // Specify the name of the bucket. Example: examplebucket. 
           String bucket = "examplebucket"; 
           // Specify the name of the host in the https://bucketname.endpoint format.                    
           String host = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com"; 
           // Specify the URL of the application server to which an upload callback request is sent. This URL is used for communication between the application server and OSS. After you upload an object, OSS uses the URL to send upload information to the application server. 
           String callbackUrl = "https://192.168.0.0:8888";
           // Specify the prefix of the object that you want to upload. You can leave this parameter empty. If you do not specify this parameter, the object is uploaded to the root directory of the bucket. 
           String dir = "exampledir/"; 
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
            try {
                long expireTime = 30;
                long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
                Date expiration = new Date(expireEndTime);
                // You can upload an object that is up to 5 GB in size by calling the PostObject operation. To upload an object that is 5 GB in size, set CONTENT_LENGTH_RANGE to 5*1024*1024*1024. 
                PolicyConditions policyConds = new PolicyConditions();
                policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
                policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
    
                String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
                byte[] binaryData = postPolicy.getBytes("utf-8");
                String accessId = credentialsProvider.getCredentials().getAccessKeyId();
                String encodedPolicy = BinaryUtil.toBase64String(binaryData);
                String postSignature = ossClient.calculatePostSignature(postPolicy);
    
                Map<String, String> respMap = new LinkedHashMap<String, String>();
                respMap.put("accessid", accessId);
                respMap.put("policy", encodedPolicy);
                respMap.put("signature", postSignature);
                respMap.put("dir", dir);
                respMap.put("host", host);
                respMap.put("expire", String.valueOf(expireEndTime / 1000));
                // respMap.put("expire", formatISO8601Date(expiration));
    
                JSONObject jasonCallback = new JSONObject();
                jasonCallback.put("callbackUrl", callbackUrl);
                jasonCallback.put("callbackBody",
                        "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
                jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
                String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
                respMap.put("callback", base64CallbackBody);
    
                JSONObject ja1 = JSONObject.fromObject(respMap);
                // System.out.println(ja1.toString());
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "GET, POST");
                response(request, response, ja1.toString());
    
            } catch (Exception e) {
                // Assert.fail(e.getMessage());
                System.out.println(e.getMessage());
            } finally { 
                ossClient.shutdown();
            }
        }
  • Upload callbacks

    protected boolean VerifyOSSCallbackRequest(HttpServletRequest request, String ossCallbackBody)
                throws NumberFormatException, IOException {
            boolean ret = false;
            String autorizationInput = new String(request.getHeader("Authorization"));
            String pubKeyInput = request.getHeader("x-oss-pub-key-url");
            byte[] authorization = BinaryUtil.fromBase64String(autorizationInput);
            byte[] pubKey = BinaryUtil.fromBase64String(pubKeyInput);
            String pubKeyAddr = new String(pubKey);
            if (!pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")
                    && !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")) {
                System.out.println("pub key addr must be oss addrss");
                return false;
            }
            String retString = executeGet(pubKeyAddr);
            retString = retString.replace("-----BEGIN PUBLIC KEY-----", "");
            retString = retString.replace("-----END PUBLIC KEY-----", "");
            String queryString = request.getQueryString();
            String uri = request.getRequestURI();
            String decodeUri = java.net.URLDecoder.decode(uri, "UTF-8");
            String authStr = decodeUri;
            if (queryString != null && !queryString.equals("")) {
                authStr += "?" + queryString;
            }
            authStr += "\n" + ossCallbackBody;
            ret = doCheck(authStr, authorization, retString);
            return ret;
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String ossCallbackBody = GetPostBody(request.getInputStream(),
                    Integer.parseInt(request.getHeader("content-length")));
            boolean ret = VerifyOSSCallbackRequest(request, ossCallbackBody);
            System.out.println("verify result : " + ret);
            // System.out.println("OSS Callback Body:" + ossCallbackBody);
            if (ret) {
                response(request, response, "{\"Status\":\"OK\"}", HttpServletResponse.SC_OK);
            } else {
                response(request, response, "{\"Status\":\"verify not ok\"}", HttpServletResponse.SC_BAD_REQUEST);
            }
        }

    For more information about the API operation that you can call to configure upload callbacks, see Callback.