表單上傳是使用HTML表單形式上傳檔案到指定儲存空間中,檔案最大不能超過5GB。
表單上傳的適用場景介紹請參見開發指南中的表單上傳。PostObject更詳情資訊請參見Java模擬PostObject表單上傳OSS。
以下代碼用於表單上傳:
public class PostObjectSample {
// 上傳檔案
private String localFilePath = "<yourLocalFile>";
// Endpoint以杭州為例,其它Region請按實際情況填寫。
private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里雲主帳號AccessKey擁有所有API的存取權限,風險很高。強烈建議您建立並使用RAM帳號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM帳號。
private String accessKeyId = "<yourAccessKeyId>";
private String accessKeySecret = "<yourAccessKeySecret>";
// 儲存空間名稱
private String bucketName = "<yourBucketName>";
// 檔案名稱
private String objectName = "<yourObjectName>";
/**
* 表單上傳
* @throws Exception
*/
private void PostObject() throws Exception {
// 在URL中添加儲存空間名稱,添加後URL如下:http://yourBucketName.oss-cn-hangzhou.aliyuncs.com
String urlStr = endpoint.replace("http://", "http://" + bucketName+ ".");
// 表單Map。
Map<String, String> formFields = new LinkedHashMap<String, String>();
// 設定檔案名稱。
formFields.put("key", this.objectName);
// 設定Content-Disposition。
formFields.put("Content-Disposition", "attachment;filename="
+ localFilePath);
// 設定回調參數。
Callback callback = new Callback();
// 設定回調伺服器位址,如http://oss-demo.aliyuncs.com:23450或http://127.0.0.1:9090。
callback.setCallbackUrl("<yourCallbackServerUrl>");
// 設定回調請求消息頭中Host的值,如oss-cn-hangzhou.aliyuncs.com。
callback.setCallbackHost("<yourCallbackServerHost>");
// 設定發起回調時請求body的值。
callback.setCallbackBody("{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}}");
// 設定發起回調請求的Content-Type。
callback.setCalbackBodyType(CalbackBodyType.JSON);
// 設定發起回調請求的自訂參數,由Key和Value組成,Key必須以x:開始。
callback.addCallbackVar("x:var1", "value1");
callback.addCallbackVar("x:var2", "value2");
// 在表單Map中設定回調參數。
setCallBack(formFields, callback);
// 設定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()));
// 設定policy。
formFields.put("policy", encodePolicy);
// 生成簽名。
String signaturecom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(accessKeySecret, encodePolicy);
// 設定簽名。
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)");
// 設定MD5值。MD5值是由整個body計算得出的。
conn.setRequestProperty("Content-MD5", "<yourContentMD5>");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 遍曆讀取表單Map中的資料,將資料寫入到輸出資料流中。
if (formFields != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Entry<String, String>> iter = formFields.entrySet().iterator();
int i = 0;
while (iter.hasNext()) {
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());
}
// 讀取檔案資訊,將要上傳的檔案寫入到輸出資料流中。
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();
// 讀取返回資料。
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 (Exception e) {
System.err.println("Send post request exception: " + e);
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 (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();
}
}