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.
Examples
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.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
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 = "http://oss-cn-hangzhou.aliyuncs.com";
// 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: 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";
/**
* 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 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: 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 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();
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)");
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.