This is a creation in Article, where the information may have evolved or changed.
This article is an upgraded version of the previous article golang+android (using httpurlconnection) for uploading files, implementing multi-file uploads, and accompanying HTTP request parameters.
Client code:
/** * Use HttpURLConnection to submit requests via post and upload files. * * @param actionurl access URL * @param textparams text type post parameter (key:value) * @param a collection of filepaths file paths * @ret Urn server returns data that returns NULL when an exception occurs */public static string Postwithfiles (string ActionURL, map<string, string> Textpar AMS, list<string> filepaths) {try {final String boundary = Uuid.randomuuid (). toString (); Final String PREFIX = "--"; Final String line_end = "\ r \ n"; Final String multipart_from_data = "Multipart/form-data"; Final String CHARSET = "UTF-8"; URL uri = new URL (actionurl); HttpURLConnection conn = (httpurlconnection) uri.openconnection (); Cache Size Conn.setchunkedstreamingmode (1024 * 64); Timeout Conn.setreadtimeout (5 * 1000); Conn.setdoinput (TRUE); Conn.setdooutput (TRUE); Conn.setusecaches (FALSE); Conn.setrequestmethod ("POST "); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Charset", "UTF-8"); Conn.setrequestproperty ("Content-type", Multipart_from_data + "; boundary=" + boundary); Splicing text type parameters StringBuilder TEXTSB = new StringBuilder (); if (textparams! = null) {for (map.entry<string, string> entry:textParams.entrySet ()) { Textsb.append (PREFIX). Append (Boundary). Append (Line_end); Textsb.append ("Content-disposition:form-data; Name=\ "" + entry.getkey () + "\" "+ line_end); Textsb.append ("Content-type:text/plain; Charset= "+ charset + line_end); Textsb.append ("Content-transfer-encoding:8bit" + line_end); Textsb.append (Line_end); Textsb.append (Entry.getvalue ()); Textsb.append (Line_end); }} dataoutputstream OutStream = new DataOutputStream (Conn.getoutputstream ()); Outstream.write (Textsb.tostring (). GetBytes ()); Parameter post mode//outstream.write ("Userid=1&cityid=26". GetBytes ()); Send file data if (filepaths! = null) {for (String file:filepaths) {Stringbuil Der Filesb = new StringBuilder (); Filesb.append (PREFIX). Append (Boundary). Append (Line_end); Filesb.append ("Content-disposition:form-data; Name=\ "File\"; Filename=\ "" + file.substring (File.lastindexof ("/") + 1) + "\" "+ line_end); Filesb.append ("Content-type:application/octet-stream; Charset= "+ charset + line_end); Filesb.append (Line_end); Outstream.write (Filesb.tostring (). GetBytes ()); InputStream is = new FileInputStream (file); byte[] buffer = new byte[1024 * 8]; int Len;while (len = is.read (buffer))! =-1) {outstream.write (buffer, 0, Len); } is.close (); Outstream.write (Line_end.getbytes ()); }}//Request End Flag Outstream.write ((PREFIX + boundary + PREFIX + line_end). GetBytes ()); Outstream.flush (); Get the response code int responsecode = Conn.getresponsecode (); BufferedReader br = new BufferedReader (New InputStreamReader (Conn.getinputstream (), CHARSET)); StringBuilder RESULTSB = null; String Line; if (Responsecode = =) {RESULTSB = new StringBuilder (); while (line = Br.readline ())! = null) {Resultsb.append (line). append ("\ n"); }} br.close (); Outstream.close (); Conn.disconnect (); return RESULTSB = = null? Null:resultSb.toString (); } catch (IOException e) {E.printstacktrace (); } return null; }
Server-side code:
The client uploads multiple files with the request parameter Func handleuploadfile (w http. Responsewriter, R *http. Request) {fmt. PRINTLN ("Client:", R.remoteaddr, "method:", R.method) R.parseform () R.parsemultipartform (<< 20)//MAX memory is 32m// Read parameter userId: = R.formvalue ("UserId") Cityid: = R.formvalue ("Cityid") log. Println ("userid=", UserId, "cityid=", Cityid) MP: = R.MULTIPARTFORMIF MP = = Nil {log. Println ("not multipartform.") W.write ([]byte) ("Not multipartform format")) Return}fileheaders, FindFile: = MP. file["file"]if!findfile | | Len (fileheaders) = = 0 {log. Println ("file count = = 0.") W.write ([]byte) ("No Upload file") Return}for _, V: = Range Fileheaders {fileName: = V.filenamefile, err: = V.open () checkErrorV2 ( Err, "Open file error." +filename) defer file. Close () Outputfilepath: = "/home/admin/Desktop/" + Filenamewriter, err: = OS. OpenFile (Outputfilepath, OS. O_wronly|os. O_create, 0666) checkErrorV2 (err, "Open local file Error") Io. Copy (writer, file)}msg: = Fmt. Sprintf ("%d files successfully uploaded", Len (fileheaders)) W.write (([]byte) (MSG)}
Note: checkErrorV2 is a simple function to check for errors.