1 Public string Starttoupload (string urlstr, file file,2 String Uploadtype) {3 4HttpURLConnection conn =NULL;5BufferedReader BufferedReader =NULL;6InputStreamReader InputStreamReader =NULL;7String boundary = "---------------------------";//boundary is the delimiter for the request header and the content of the uploaded file8 Try {9URL url =NewURL (URLSTR);Tenconn =(HttpURLConnection) url.openconnection (); OneConn.setconnecttimeout (5000); AConn.setreadtimeout (30000); -Conn.setdooutput (true); -Conn.setdoinput (true); theConn.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); A atOutputStream out =NewDataOutputStream (Conn.getoutputstream ()); - -String filename =file.getname (); - -StringBuffer strbuf =NewStringBuffer (); -Strbuf.append ("\ r \ n"). Append ("--"). Append (Boundary). Append ("\ r \ n"); inStrbuf.append ("Content-disposition:form-data; Name=\ "File\"; Filename=\ "" -+ filename + "\" \ "\ \"); toStrbuf.append ("Content-type:" + uploadtype + "\r\n\r\n"); + - Out.write (Strbuf.tostring (). GetBytes ()); the *DataInputStream in =NewDataInputStream (Newfileinputstream (file)); $ intbytes = 0;Panax Notoginseng byte[] Bufferout =New byte[1024]; - while((bytes = In.read (bufferout))! =-1) { theOut.write (bufferout, 0, bytes); + } A in.close (); the + byte[] Enddata = ("\r\n--" + boundary + "--\r\n"). GetBytes (); - Out.write (enddata); $ Out.flush (); $ out.close (); - - //Read return Data theStringBuffer strBuf2 =NewStringBuffer (); -InputStreamReader =NewInputStreamReader (Conn.getinputstream (),Wuyi"UTF-8"); theBufferedReader =NewBufferedReader (inputstreamreader); -String line =NULL; Wu while(line = Bufferedreader.readline ())! =NULL) { -Strbuf2.append (line) append ("\ n"); About } $ -Jsonobject Jsonarray =Jsonobject.fromobject (strbuf2.tostring ()); - - Booleanuploadsuccess = Jsonarray.getboolean ("ReturnCode"); A + if(uploadsuccess) { the return""; - } $ theUrlstr = jsonarray.getstring ("resultmsg"); the}Catch(Exception e) { the e.printstacktrace (); the returne.getmessage (); -}finally { in Try { the if(Conn! =NULL) { the Conn.disconnect (); About } the if(InputStreamReader! =NULL) { the inputstreamreader.close (); the } + if(BufferedReader! =NULL) { - bufferedreader.close (); the }Bayi}Catch(IOException e) { the e.printstacktrace (); the } - } - returnUrlstr; the } the
Java implementation File Upload