首页 > 开发 > Java > 正文

java通过模拟post方式提交表单实现图片上传功能实例

2024-07-13 09:55:56
字体:
来源:转载
供稿:网友

这篇文章主要介绍了java通过模拟post方式提交表单实现图片上传功能实例,涉及Java针对表单的提交操作响应及文件传输的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了java通过模拟post方式提交表单实现图片上传功能。分享给大家供大家参考,具体如下:

模拟表单html如下:

 

 
  1. <form action="up_result.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1"
  2. <label> 
  3. <input type="text" name="name" value="" /> 
  4. </label> 
  5. <label> 
  6. <input type="file" name="userfile" /> 
  7. </label> 
  8. <label> 
  9. <input type="submit" value="上传" /> 
  10. </label> 
  11. </form> 

java代码如下:

 

 
  1. package com.yanek.util;  
  2. import java.io.BufferedReader;  
  3. import java.io.DataInputStream;  
  4. import java.io.DataOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.InputStreamReader;  
  8. import java.io.OutputStream;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11. import java.util.HashMap;  
  12. import java.util.Iterator;  
  13. import java.util.Map;  
  14. import javax.activation.MimetypesFileTypeMap;  
  15. import net.sf.json.JSONArray;  
  16. import net.sf.json.JSONObject;  
  17. public class HttpPostUploadUtil {  
  18. /**  
  19. * @param args  
  20. */ 
  21. public static void main(String[] args) {  
  22. String filepath="E://ziliao//0.jpg";  
  23. String urlStr = "http://127.0.0.1:8080/minicms/up/up_result.jsp";  
  24. Map<String, String> textMap = new HashMap<String, String>();  
  25. textMap.put("name""testname");  
  26. Map<String, String> fileMap = new HashMap<String, String>();  
  27. fileMap.put("userfile", filepath);  
  28. String ret = formUpload(urlStr, textMap, fileMap);  
  29. System.out.println(ret);  
  30. }  
  31. /**  
  32. * 上传图片  
  33.  
  34. * @param urlStr  
  35. * @param textMap  
  36. * @param fileMap  
  37. * @return  
  38. */ 
  39. public static String formUpload(String urlStr, Map<String, String> textMap, 
  40. Map<String, String> fileMap) {  
  41. String res = "";  
  42. HttpURLConnection conn = null;  
  43. String BOUNDARY = "---------------------------123821742118716"//boundary就是request头和上传文件内容的分隔符  
  44. try {  
  45. URL url = new URL(urlStr);  
  46. conn = (HttpURLConnection) url.openConnection();  
  47. conn.setConnectTimeout(5000);  
  48. conn.setReadTimeout(30000);  
  49. conn.setDoOutput(true);  
  50. conn.setDoInput(true);  
  51. conn.setUseCaches(false);  
  52. conn.setRequestMethod("POST");  
  53. conn.setRequestProperty("Connection""Keep-Alive");  
  54. conn  
  55. .setRequestProperty("User-Agent",  
  56. "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
  57. conn.setRequestProperty("Content-Type",  
  58. "multipart/form-data; boundary=" + BOUNDARY);  
  59. OutputStream out = new DataOutputStream(conn.getOutputStream());  
  60. // text  
  61. if (textMap != null) {  
  62. StringBuffer strBuf = new StringBuffer();  
  63. Iterator iter = textMap.entrySet().iterator();  
  64. while (iter.hasNext()) {  
  65. Map.Entry entry = (Map.Entry) iter.next();  
  66. String inputName = (String) entry.getKey();  
  67. String inputValue = (String) entry.getValue();  
  68. if (inputValue == null) {  
  69. continue;  
  70. }  
  71. strBuf.append("/r/n").append("--").append(BOUNDARY).append(  
  72. "/r/n");  
  73. strBuf.append("Content-Disposition: form-data; name=/"" 
  74. + inputName + "/"/r/n/r/n");  
  75. strBuf.append(inputValue);  
  76. }  
  77. out.write(strBuf.toString().getBytes());  
  78. }  
  79. // file  
  80. if (fileMap != null) {  
  81. Iterator iter = fileMap.entrySet().iterator();  
  82. while (iter.hasNext()) {  
  83. Map.Entry entry = (Map.Entry) iter.next();  
  84. String inputName = (String) entry.getKey();  
  85. String inputValue = (String) entry.getValue();  
  86. if (inputValue == null) {  
  87. continue;  
  88. }  
  89. File file = new File(inputValue);  
  90. String filename = file.getName();  
  91. String contentType = new MimetypesFileTypeMap()  
  92. .getContentType(file);  
  93. if (filename.endsWith(".png")) {  
  94. contentType = "image/png";  
  95. }  
  96. if (contentType == null || contentType.equals("")) {  
  97. contentType = "application/octet-stream";  
  98. }  
  99. StringBuffer strBuf = new StringBuffer();  
  100. strBuf.append("/r/n").append("--").append(BOUNDARY).append(  
  101. "/r/n");  
  102. strBuf.append("Content-Disposition: form-data; name=/"" 
  103. + inputName + "/"; filename=/"" + filename  
  104. "/"/r/n");  
  105. strBuf.append("Content-Type:" + contentType + "/r/n/r/n");  
  106. out.write(strBuf.toString().getBytes());  
  107. DataInputStream in = new DataInputStream(  
  108. new FileInputStream(file));  
  109. int bytes = 0;  
  110. byte[] bufferOut = new byte[1024];  
  111. while ((bytes = in.read(bufferOut)) != -1) {  
  112. out.write(bufferOut, 0, bytes);  
  113. }  
  114. in.close();  
  115. }  
  116. }  
  117. byte[] endData = ("/r/n--" + BOUNDARY + "--/r/n").getBytes();  
  118. out.write(endData);  
  119. out.flush();  
  120. out.close();  
  121. // 读取返回数据  
  122. StringBuffer strBuf = new StringBuffer();  
  123. BufferedReader reader = new BufferedReader(new InputStreamReader(  
  124. conn.getInputStream()));  
  125. String line = null;  
  126. while ((line = reader.readLine()) != null) {  
  127. strBuf.append(line).append("/n");  
  128. }  
  129. res = strBuf.toString();  
  130. reader.close();  
  131. reader = null;  
  132. catch (Exception e) {  
  133. System.out.println("发送POST请求出错。" + urlStr);  
  134. e.printStackTrace();  
  135. finally {  
  136. if (conn != null) {  
  137. conn.disconnect();  
  138. conn = null;  
  139. }  
  140. }  
  141. return res;  
  142. }  

希望本文所述对大家Java程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表