Java analog Post method submission form implementation picture upload "Go"

Source: Internet
Author: User

Turn from:http://blog.csdn.net/5iasp/article/details/8669644

The simulation form HTML is as follows:

 <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= "upload"/>  </label></form>  java code as follows:  [java] View plain copypackage 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) {     &N Bsp             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& Lt String, string> ();                textmap.put ("name", "TestName");            map<string, string> filemap = new hashmap<string, string> ();                    FILEMAP.PUT ("file", filepath);                    String ret = formupload (Urlstr, Textmap, Filemap );                    SYSTEM.OUT.PRINTLN (ret);                 }            & nbsp;      /**      * uploading images       *       * @param urlstr      * @param textmap      * @param filemap   &NB Sp  * @return       */     public static string Formupload (String urlstr, Map<str ING, string> textmap,              map<string, string> filemap) {         String res = "";          HttpURLConnection conn = null;          String BOundary = "---------------------------123821742118716"; Boundary is the delimiter for the request header and the contents of the uploaded file          try {             UR L 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"                              "Moz illa/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! = nul L) {                 StringBuffer strbuf = new StringBuffer ();                  Iterator iter = Textmap.entryset (). Iterator ();                  while (Iter.hasnext ()) {         & nbsp     &nbsp     Map.entry Entry = (map.entry) iter.next ();                      String inputname = (String) entry.getkey ();                      String inputvalue = (String) entry.getvalue ();                      if (Inputvalue = = null) {                         continue;                     }            &NB Sp         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);                         &NB Sp Out.write (Strbuf.tostring (). GetBytes ());             }               //File &nbs p;            if (filemap! = null) {                 Iterator iter = Filemap.entryset (). Iterator ();                  while (Iter.hasnext ()) {         & nbsp           Map.entry Entry = (map.entry) iter.next ();                      String inputname = (String) entry.getkey ();                      String inputvalue = (String) entry.getvalue ();                      if (Inputvalue = = null) {                         continue;                     }            &NB Sp         File File = new file (inputvalue);                      String filename = File.getname ();                      String contentType = new Mimetypesfiletypemap (                              getContentType ( file);                      if (Filename.endswith (". png")) {     &NBSp                   ContentType = "Image/png";                     }            &NB Sp         if (ContentType = = NULL | | contenttype.equals ("")) {                         ContentType = "Application/octet-stream";                     }          &NBSP ;             StringBuffer strbuf = new StringBuffer ();                      strbuf.append ("\ r \ n"). Append ("--"). Append ( Boundary). Append (                             "\ r \ n");                      Strbuf.append ("Content-disposition: Form-data; Name=\ ""                              + Inputna Me + "\"; Filename=\ "" + filename                            and nbsp + "\" \ r \ n ");                      Strbuf.append ("Content-type:" + ContentType + "\r\n\r\n");                        Out.write (strbuf.tostring (). GetBytes ());                        DataInputStream in = new Datainput Stream (                             New Filein Putstream (file));                      int bytes = 0;                      byte[] Bufferout = NEW byte[1024];                      while ((bytes = In.read (bufferout))! =-1) {& nbsp;                        Out.write (bufferout, 0, bytes);                     }            &NB Sp         in.close ();                       &NBSP;&N bsp;             byte[] Enddata = ("\r\n--" + boundary + "--\r\n"). GetBytes ();              Out.write (enddata);              Out.flush ();              out.close ();               //Read back data              Stri Ngbuffer strbuf = new STRINGBUffer ();              BufferedReader reader = new BufferedReader (New InputStreamReader (&NBSP;&N Bsp                 Conn.getinputstream ()));              String line = null;              while (line = Reader.readline ()) = null) {       &N Bsp         Strbuf.append (line) append ("\ n");             }              res = strbuf.tostring ();              reader.close ();              reader = null;         } catch (Exception e) {             System.out.print ln ("Error sending post request.") "+ urlstr);              e.printstacktrace ();         } finally {             IF (conn! = null) {               &NB Sp Conn.disconnect ();                  conn = null;             }         }          RE Turn res;     }    }

Java analog Post method submission form implementation picture upload "Go"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.