1. 程式人生 > >java模擬post方式提交表單實現圖片上傳

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程式碼如下:

  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. publicclass HttpPostUploadUtil {  
  18.     /** 
  19.      * @param args 
  20.      */
  21.     publicstatic
    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.     publicstatic 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 = newbyte[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.     }  
  143. }