欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-07 19:13:27
本文实例讲述了java通过模拟post方式提交表单实现图片上传功能。分享给大家供大家参考,具体如下: 模拟表单html如下:

本文实例讲述了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代码如下:

package com.yanek.util; 
import java.io.bufferedreader; 
import java.io.datainputstream; 
import java.io.dataoutputstream; 
import java.io.file; 
import java.io.fileinputstream; 
import java.io.inputstreamreader; 
import java.io.outputstream; 
import java.net.httpurlconnection; 
import java.net.url; 
import java.util.hashmap; 
import java.util.iterator; 
import java.util.map; 
import javax.activation.mimetypesfiletypemap; 
import net.sf.json.jsonarray; 
import net.sf.json.jsonobject; 
public class httppostuploadutil { 
 /** 
  * @param args 
  */ 
 public static void main(string[] args) { 
  string filepath="e:\\ziliao\\0.jpg"; 
  string urlstr = "http://127.0.0.1:8080/minicms/up/up_result.jsp"; 
  map<string, string> textmap = new hashmap<string, string>(); 
  textmap.put("name", "testname"); 
  map<string, string> filemap = new hashmap<string, string>(); 
  filemap.put("userfile", filepath); 
  string ret = formupload(urlstr, textmap, filemap); 
  system.out.println(ret); 
 } 
 /** 
  * 上传图片 
  * 
  * @param urlstr 
  * @param textmap 
  * @param filemap 
  * @return 
  */ 
 public static string formupload(string urlstr, map<string, string> textmap,
   map<string, string> filemap) { 
  string res = ""; 
  httpurlconnection conn = null; 
  string boundary = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符 
  try { 
   url url = new url(urlstr); 
   conn = (httpurlconnection) url.openconnection(); 
   conn.setconnecttimeout(5000); 
   conn.setreadtimeout(30000); 
   conn.setdooutput(true); 
   conn.setdoinput(true); 
   conn.setusecaches(false); 
   conn.setrequestmethod("post"); 
   conn.setrequestproperty("connection", "keep-alive"); 
   conn 
     .setrequestproperty("user-agent", 
       "mozilla/5.0 (windows; u; windows nt 6.1; zh-cn; rv:1.9.2.6)"); 
   conn.setrequestproperty("content-type", 
     "multipart/form-data; boundary=" + boundary); 
   outputstream out = new dataoutputstream(conn.getoutputstream()); 
   // text 
   if (textmap != null) { 
    stringbuffer strbuf = new stringbuffer(); 
    iterator iter = textmap.entryset().iterator(); 
    while (iter.hasnext()) { 
     map.entry entry = (map.entry) iter.next(); 
     string inputname = (string) entry.getkey(); 
     string inputvalue = (string) entry.getvalue(); 
     if (inputvalue == null) { 
      continue; 
     } 
     strbuf.append("\r\n").append("--").append(boundary).append( 
       "\r\n"); 
     strbuf.append("content-disposition: form-data; name=\"" 
       + inputname + "\"\r\n\r\n"); 
     strbuf.append(inputvalue); 
    } 
    out.write(strbuf.tostring().getbytes()); 
   } 
   // file 
   if (filemap != null) { 
    iterator iter = filemap.entryset().iterator(); 
    while (iter.hasnext()) { 
     map.entry entry = (map.entry) iter.next(); 
     string inputname = (string) entry.getkey(); 
     string inputvalue = (string) entry.getvalue(); 
     if (inputvalue == null) { 
      continue; 
     } 
     file file = new file(inputvalue); 
     string filename = file.getname(); 
     string contenttype = new mimetypesfiletypemap() 
       .getcontenttype(file); 
     if (filename.endswith(".png")) { 
      contenttype = "image/png"; 
     } 
     if (contenttype == null || contenttype.equals("")) { 
      contenttype = "application/octet-stream"; 
     } 
     stringbuffer strbuf = new stringbuffer(); 
     strbuf.append("\r\n").append("--").append(boundary).append( 
       "\r\n"); 
     strbuf.append("content-disposition: form-data; name=\"" 
       + inputname + "\"; filename=\"" + filename 
       + "\"\r\n"); 
     strbuf.append("content-type:" + contenttype + "\r\n\r\n"); 
     out.write(strbuf.tostring().getbytes()); 
     datainputstream in = new datainputstream( 
       new fileinputstream(file)); 
     int bytes = 0; 
     byte[] bufferout = new byte[1024]; 
     while ((bytes = in.read(bufferout)) != -1) { 
      out.write(bufferout, 0, bytes); 
     } 
     in.close(); 
    } 
   } 
   byte[] enddata = ("\r\n--" + boundary + "--\r\n").getbytes(); 
   out.write(enddata); 
   out.flush(); 
   out.close(); 
   // 读取返回数据 
   stringbuffer strbuf = new stringbuffer(); 
   bufferedreader reader = new bufferedreader(new inputstreamreader( 
     conn.getinputstream())); 
   string line = null; 
   while ((line = reader.readline()) != null) { 
    strbuf.append(line).append("\n"); 
   } 
   res = strbuf.tostring(); 
   reader.close(); 
   reader = null; 
  } catch (exception e) { 
   system.out.println("发送post请求出错。" + urlstr); 
   e.printstacktrace(); 
  } finally { 
   if (conn != null) { 
    conn.disconnect(); 
    conn = null; 
   } 
  } 
  return res; 
 } 
}

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