You can use an HTML form to upload an object up to 5 GB in size to a specified bucket. This upload method is called form upload. This topic describes how to perform form upload in Object Storage Service (OSS).

Sample code

The following code provides an example on how to perform form upload:

package com.aliyun.oss;

import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.internal.OSSUtils;
import com.aliyun.oss.model.Callback;
import org.apache.commons.codec.binary.Base64;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class PostObjectSample {
    // Specify the full path of the local file that you want to upload. 
    private String localFilePath = "yourLocalFile";
    // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
    private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 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 RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    private String accessKeyId = "yourAccessKeyId";
    private String accessKeySecret = "yourAccessKeySecret";
    // Specify the name of the bucket. 
    private String bucketName = "yourBucketName";
    // Specify the full path of the object. The path cannot contain the bucket name. 
    private String objectName = "yourObjectName";
    // Specify the URL of the server to which you want to send the callback request. Example: http://oss-demo.oss-cn-hangzhou.aliyuncs.com:23450 or http://127.0.0.1:9090. 
    private String callbackServerUrl = "yourCallbackServerUrl";
    // Specify the Host header in the callback request. Example: oss-cn-hangzhou.aliyuncs.com. 
    private String callbackServerHost = "yourCallbackServerHost";
    // Specify the MD5 hash. The MD5 hash is calculated based on the entire body. 
    private static String contentMD5 = "yourContentMD5";
    /**
     * Perform form upload. 
     * @throws Exception
     */
    private void PostObject() throws Exception {
        // Add the bucket name to the URL. The URL format is http://yourBucketName.oss-cn-hangzhou.aliyuncs.com. 
        String urlStr = endpoint.replace("http://", "http://" + bucketName+ ".");
        // Specify Map for the form. 
        Map<String, String> formFields = new LinkedHashMap<String, String>();
        // Specify the object name. 
        formFields.put("key", this.objectName);
        // Specify Content-Disposition. 
        formFields.put("Content-Disposition", "attachment;filename="
                + localFilePath);
        // Specify callback parameters. For more information about callbacks, see Callback. 
        // Callback callback = new Callback();
        // Specify the URL of the server to which you want to send the callback request. Example: http://oss-demo.oss-cn-hangzhou.aliyuncs.com:23450 or http://127.0.0.1:9090. 
        // callback.setCallbackUrl(callbackServerUrl);
        // Specify the Host header in the callback request. Example: oss-cn-hangzhou.aliyuncs.com. 
        // callback.setCallbackHost(callbackServerHost);
        // Specify the value of the body field included in the callback request. 
        // callback.setCallbackBody("{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}}");
        // Specify Content-Type in the callback request. 
        // callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
        // Specify the custom parameters used to send the callback request. Each custom parameter consists of a key-value pair. The key must start with x: and be in lower case. 
        // callback.addCallbackVar("x:var1", "value1");
        // callback.addCallbackVar("x:var2", "value2");
        // Specify the callback parameter in Map for the form. 
        // setCallBack(formFields, callback);
        // Specify OSSAccessKeyId. 
        formFields.put("OSSAccessKeyId", accessKeyId);
        String policy = "{\"expiration\": \"2120-01-01T12:00:00.000Z\",\"conditions\": [[\"content-length-range\", 0, 104857600]]}";
        String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
        // Specify the policy. 
        formFields.put("policy", encodePolicy);
        // Generate a signature. 
        String signaturecom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(accessKeySecret, encodePolicy);
        // Add the signature to the policy. 
        formFields.put("Signature", signaturecom);
        String ret = formUpload(urlStr, formFields, localFilePath);
        System.out.println("Post Object [" + this.objectName + "] to bucket [" + bucketName + "]");
        System.out.println("post reponse:" + ret);
    }
    private static String formUpload(String urlStr, Map<String, String> formFields, String localFile)
            throws Exception {
        String res = "";
        HttpURLConnection conn = null;
        String boundary = "9431149156168";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            // Specify the MD5 hash. The MD5 hash is calculated based on the entire body. You can configure MD5 encryption settings to enable MD5 verification. 
            // conn.setRequestProperty("Content-MD5", contentMD5);
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // Recursively read all Map data for the form and write the data to the output stream. 
            if (formFields != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator<Map.Entry<String, String>> iter = formFields.entrySet().iterator();
                int i = 0;
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    if (i == 0) {
                        strBuf.append("--").append(boundary).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
                        strBuf.append(inputValue);
                    } else {
                        strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
                        strBuf.append(inputValue);
                    }
                    i++;
                }
                out.write(strBuf.toString().getBytes());
            }
            // Read the file and write it to the output stream. 
            File file = new File(localFile);
            String filename = file.getName();
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }
            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(boundary)
                    .append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"file\"; "
                    + "filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
            out.write(strBuf.toString().getBytes());
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // Read returned data. 
            strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (ClientException e) {
//            System.err.println("Send post request exception: " + e);
            System.err.println(e.getErrorCode()+" msg="+e.getMessage());
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
    private static void setCallBack(Map<String, String> formFields, Callback callback) {
        if (callback != null) {
            String jsonCb = OSSUtils.jsonizeCallback(callback);
            String base64Cb = BinaryUtil.toBase64String(jsonCb.getBytes());
            formFields.put("callback", base64Cb);
            if (callback.hasCallbackVar()) {
                Map<String, String> varMap = callback.getCallbackVar();
                for (Map.Entry<String, String> entry : varMap.entrySet()) {
                    formFields.put(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    public static void main(String[] args) throws Exception {
        PostObjectSample ossPostObject = new PostObjectSample();
        ossPostObject.PostObject();
    }
}

References

For more information about the API operation that you can call to perform form upload, see PostObject.