Golang + Android implements file upload (Multifile upload with request parameters) and golangandroid
This article is an upgraded version of Golang + Android (using HttpURLConnection) to implement Multifile upload, with http Request Parameters attached.
Client code:
/*** Use HttpURLConnection to submit a request through POST and upload the file. ** @ Param actionUrl: url * @ param textParams POST parameter (key: value) * @ param filePaths file path set * @ return data returned by the server, return null */public static String postWithFiles (String actionUrl, Map <String, String> textParams, 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. set RequestProperty ("Charset", "UTF-8"); conn. setRequestProperty ("Content-Type", MULTIPART_FROM_DATA + "; boundary =" + BOUNDARY); // concatenate the 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 (ent Ry. getValue (); textSb. append (LINE_END) ;}} DataOutputStream outStream = new DataOutputStream (conn. getOutputStream (); outStream. write (textSb. toString (). getBytes (); // parameter POST method // outStream. write ("userId = 1 & cityId = 26 ". getBytes (); // send the file data if (filePaths! = Null) {for (String file: filePaths) {StringBuilder 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); outStr Eam. 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 () ;}// the end mark of the Request 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 (responseCod E = 200) {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 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 (32 <20) // The maximum memory size is 32 MB. // read the 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 Mul TipartForm format ") return} fileHeaders, findFile: = mp. File [" file "] if! FindFile | len (fileHeaders) = 0 {log. println ("file count = 0. ") w. write ([] byte) ("No File Uploaded") 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 uploaded successfully", len (fileHeaders) w. write ([] byte) (msg ))}
Note: checkErrorV2 is a simple function for checking errors.