全部產品
Search
文件中心

Object Storage Service:表單上傳

更新時間:Aug 30, 2018

表單上傳是使用HTML表單形式上傳檔案到指定儲存空間中,檔案最大不能超過5GB。

表單上傳的適用場景介紹請參見開發指南中的表單上傳。PostObject更詳情資訊請參見Java模擬PostObject表單上傳OSS

以下代碼用於表單上傳:

  1. public class PostObjectSample {
  2. // 上傳檔案
  3. private String localFilePath = "<yourLocalFile>";
  4. // Endpoint以杭州為例,其它Region請按實際情況填寫。
  5. private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  6. // 阿里雲主帳號AccessKey擁有所有API的存取權限,風險很高。強烈建議您建立並使用RAM帳號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM帳號。
  7. private String accessKeyId = "<yourAccessKeyId>";
  8. private String accessKeySecret = "<yourAccessKeySecret>";
  9. // 儲存空間名稱
  10. private String bucketName = "<yourBucketName>";
  11. // 檔案名稱
  12. private String objectName = "<yourObjectName>";
  13. /**
  14. * 表單上傳
  15. * @throws Exception
  16. */
  17. private void PostObject() throws Exception {
  18. // 在URL中添加儲存空間名稱,添加後URL如下:http://yourBucketName.oss-cn-hangzhou.aliyuncs.com
  19. String urlStr = endpoint.replace("http://", "http://" + bucketName+ ".");
  20. // 表單Map。
  21. Map<String, String> formFields = new LinkedHashMap<String, String>();
  22. // 設定檔案名稱。
  23. formFields.put("key", this.objectName);
  24. // 設定Content-Disposition。
  25. formFields.put("Content-Disposition", "attachment;filename="
  26. + localFilePath);
  27. // 設定回調參數。
  28. Callback callback = new Callback();
  29. // 設定回調伺服器位址,如http://oss-demo.aliyuncs.com:23450或http://127.0.0.1:9090。
  30. callback.setCallbackUrl("<yourCallbackServerUrl>");
  31. // 設定回調請求消息頭中Host的值,如oss-cn-hangzhou.aliyuncs.com。
  32. callback.setCallbackHost("<yourCallbackServerHost>");
  33. // 設定發起回調時請求body的值。
  34. callback.setCallbackBody("{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}}");
  35. // 設定發起回調請求的Content-Type。
  36. callback.setCalbackBodyType(CalbackBodyType.JSON);
  37. // 設定發起回調請求的自訂參數,由Key和Value組成,Key必須以x:開始。
  38. callback.addCallbackVar("x:var1", "value1");
  39. callback.addCallbackVar("x:var2", "value2");
  40. // 在表單Map中設定回調參數。
  41. setCallBack(formFields, callback);
  42. // 設定OSSAccessKeyId。
  43. formFields.put("OSSAccessKeyId", accessKeyId);
  44. String policy = "{\"expiration\": \"2120-01-01T12:00:00.000Z\",\"conditions\": [[\"content-length-range\", 0, 104857600]]}";
  45. String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
  46. // 設定policy。
  47. formFields.put("policy", encodePolicy);
  48. // 生成簽名。
  49. String signaturecom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(accessKeySecret, encodePolicy);
  50. // 設定簽名。
  51. formFields.put("Signature", signaturecom);
  52. String ret = formUpload(urlStr, formFields, localFilePath);
  53. System.out.println("Post Object [" + this.objectName + "] to bucket [" + bucketName + "]");
  54. System.out.println("post reponse:" + ret);
  55. }
  56. private static String formUpload(String urlStr, Map<String, String> formFields, String localFile)
  57. throws Exception {
  58. String res = "";
  59. HttpURLConnection conn = null;
  60. String boundary = "9431149156168";
  61. try {
  62. URL url = new URL(urlStr);
  63. conn = (HttpURLConnection) url.openConnection();
  64. conn.setConnectTimeout(5000);
  65. conn.setReadTimeout(30000);
  66. conn.setDoOutput(true);
  67. conn.setDoInput(true);
  68. conn.setRequestMethod("POST");
  69. conn.setRequestProperty("User-Agent",
  70. "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
  71. // 設定MD5值。MD5值是由整個body計算得出的。
  72. conn.setRequestProperty("Content-MD5", "<yourContentMD5>");
  73. conn.setRequestProperty("Content-Type",
  74. "multipart/form-data; boundary=" + boundary);
  75. OutputStream out = new DataOutputStream(conn.getOutputStream());
  76. // 遍曆讀取表單Map中的資料,將資料寫入到輸出資料流中。
  77. if (formFields != null) {
  78. StringBuffer strBuf = new StringBuffer();
  79. Iterator<Entry<String, String>> iter = formFields.entrySet().iterator();
  80. int i = 0;
  81. while (iter.hasNext()) {
  82. Entry<String, String> entry = iter.next();
  83. String inputName = entry.getKey();
  84. String inputValue = entry.getValue();
  85. if (inputValue == null) {
  86. continue;
  87. }
  88. if (i == 0) {
  89. strBuf.append("--").append(boundary).append("\r\n");
  90. strBuf.append("Content-Disposition: form-data; name=\""
  91. + inputName + "\"\r\n\r\n");
  92. strBuf.append(inputValue);
  93. } else {
  94. strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
  95. strBuf.append("Content-Disposition: form-data; name=\""
  96. + inputName + "\"\r\n\r\n");
  97. strBuf.append(inputValue);
  98. }
  99. i++;
  100. }
  101. out.write(strBuf.toString().getBytes());
  102. }
  103. // 讀取檔案資訊,將要上傳的檔案寫入到輸出資料流中。
  104. File file = new File(localFile);
  105. String filename = file.getName();
  106. String contentType = new MimetypesFileTypeMap().getContentType(file);
  107. if (contentType == null || contentType.equals("")) {
  108. contentType = "application/octet-stream";
  109. }
  110. StringBuffer strBuf = new StringBuffer();
  111. strBuf.append("\r\n").append("--").append(boundary)
  112. .append("\r\n");
  113. strBuf.append("Content-Disposition: form-data; name=\"file\"; "
  114. + "filename=\"" + filename + "\"\r\n");
  115. strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
  116. out.write(strBuf.toString().getBytes());
  117. DataInputStream in = new DataInputStream(new FileInputStream(file));
  118. int bytes = 0;
  119. byte[] bufferOut = new byte[1024];
  120. while ((bytes = in.read(bufferOut)) != -1) {
  121. out.write(bufferOut, 0, bytes);
  122. }
  123. in.close();
  124. byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
  125. out.write(endData);
  126. out.flush();
  127. out.close();
  128. // 讀取返回資料。
  129. strBuf = new StringBuffer();
  130. BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  131. String line = null;
  132. while ((line = reader.readLine()) != null) {
  133. strBuf.append(line).append("\n");
  134. }
  135. res = strBuf.toString();
  136. reader.close();
  137. reader = null;
  138. } catch (Exception e) {
  139. System.err.println("Send post request exception: " + e);
  140. throw e;
  141. } finally {
  142. if (conn != null) {
  143. conn.disconnect();
  144. conn = null;
  145. }
  146. }
  147. return res;
  148. }
  149. private static void setCallBack(Map<String, String> formFields, Callback callback) {
  150. if (callback != null) {
  151. String jsonCb = OSSUtils.jsonizeCallback(callback);
  152. String base64Cb = BinaryUtil.toBase64String(jsonCb.getBytes());
  153. formFields.put("callback", base64Cb);
  154. if (callback.hasCallbackVar()) {
  155. Map<String, String> varMap = callback.getCallbackVar();
  156. for (Entry<String, String> entry : varMap.entrySet()) {
  157. formFields.put(entry.getKey(), entry.getValue());
  158. }
  159. }
  160. }
  161. }
  162. public static void main(String[] args) throws Exception {
  163. PostObjectSample ossPostObject = new PostObjectSample();
  164. ossPostObject.PostObject();
  165. }
  166. }