全部产品
阿里云办公

表单上传

更新时间:2018-07-26 14:33:18

表单上传是使用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. }