java模拟post方式提交表单实现图片上传

模拟表单html如下:

 

<form action="up_result.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
 
    <label>
  <input type="text" name="name" value="" />
  </label>
  
    <label>
  <input type="file" name="userfile" />
  </label>
  
  <label>
  <input type="submit" value="上传" />
  </label>
</form>

 

 

java代码如下:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值