All Products
Document Center

Object Storage Service:Form upload

Last Updated:Dec 06, 2023

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

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

  • To perform form upload, you must have the oss:PutObject permission. For more information, see Attach a custom policy to a RAM user.


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

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.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import com.aliyun.oss.ClientException;

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 your actual endpoint. 
    private String endpoint = "";
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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. 
    String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
    String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");
    // Specify the name of the bucket. 
    private String bucketName = "yourBucketName";
    // Specify the full path of the object. Do not include the bucket name in the full path. 
    private String objectName = "yourObjectName";
    // Specify the URL of the server to which you want to send the callback request. Example: or 
    private String callbackServerUrl = "yourCallbackServerUrl";
    // Specify the Host header in the callback request. Example: 
    private String callbackServerHost = "yourCallbackServerHost";    
     * Perform form upload. 
     * @throws Exception
    private void PostObject() throws Exception {
        // Add the bucket name to the URL. The URL format is 
        String urlStr = endpoint.replace("http://", "http://" + bucketName+ ".");
        // Specify Map for the form. 
        Map<String, String> formFields = new LinkedHashMap<String, String>();
        // Specify the name of the object. 
        formFields.put("key", this.objectName);
        // Specify Content-Disposition. 
        formFields.put("Content-Disposition", "attachment;filename="
                + localFilePath);
        // Specify callback parameters. 
        // Callback callback = new Callback();
        // Specify the URL of the server to which you want to send the callback request. Example: or 
        // callback.setCallbackUrl(callbackServerUrl);
        // Specify the Host header in the callback request. Example: 
        // 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 in 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();
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:");            
                    "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 =;
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();
                    if (inputValue == null) {
                    if (i == 0) {
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
                    } else {
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
            // 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("Content-Disposition: form-data; name=\"file\"; "
                    + "filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = != -1) {
                out.write(bufferOut, 0, bytes);
            byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
            // Read returned data. 
            strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
            res = strBuf.toString();
            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 = 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();


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