Golang + Android (using HttpURLConnection) for File Upload
This article demonstrates how to use the Android program as the client (using HttpURLConnection to access the network) and the Golang program as the server side to upload files.
Client code:
Public static String uploadFile (String uploadUrl, String filePath) {Log. v (TAG, "url:" + uploadUrl); Log. v (TAG, "filePath:" + filePath); String nextLine = "\ r \ n"; String dividerStart = "--"; string boundary = "*******"; try {URL url = new URL (uploadUrl); HttpURLConnection connection = (HttpURLConnection) url. openConnection (); connection. setChunkedStreamingMode (1024*256); connection. setDoInput (tru E); connection. setDoOutput (true); connection. setUseCaches (false); connection. setRequestMethod ("POST"); // sets the Http Request Header connection. setRequestProperty ("Connection", "Keep-Alive"); connection. setRequestProperty ("Charset", "UTF-8"); // you must specify the delimiter connection in the Content-Type request header. setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + boundary); // define the data Writing stream and prepare to upload the file DataOutputStream dos = new DataOutputS Tream (connection. getOutputStream (); dos. writeBytes (dividerStart + boundary + nextLine); // sets the dos information related to the uploaded file. writeBytes ("Content-Disposition: form-data; name = \" file \ "; filename = \" "+ filePath. substring (filePath. lastIndexOf ("/") + 1) + "\" "+ nextLine); dos. writeBytes (nextLine); FileInputStream FCM = new FileInputStream (filePath); byte [] buffer = new byte [1024*32]; int count; // read the file content and write it to OutputSt Ream object while (count = FS. read (buffer ))! =-1) {dos. write (buffer, 0, count);} FD. close (); dos. writeBytes (nextLine); dos. writeBytes (dividerStart + boundary + dividerStart + nextLine); dos. flush (); // start to read the information transmitted from the server. InputStream is = connection. getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is, "UTF-8"); String result = br. readLine (); dos. close (); is. close (); connection. disconnect (); return result;} catch (IOException e) {e. printStackTrace ();} return null ;}
Server code:
Package webserver // receives files uploaded by the client over http // Date: 16: 18: 33 import ("fmt" "io/ioutil" "log" "net/http" "OS") func UpLoadBase () {fmt. println ("This is uploadbase") http. handleFunc ("/httpUploadFile", handleUploadFile) http. listenAndServe (": 8086", nil) if err! = Nil {fmt. println ("ListenAndServe error:", err. error ()} func handleUploadFile (w http. responseWriter, r * http. request) {fmt. println ("client:", r. remoteAddr) file, fileHeader, err: = r. formFile ("file") if err! = Nil {log. Fatal ("FormFile:", err. Error () return} defer func () {if err: = file. Close (); err! = Nil {log. fatal ("Close:", err. error () return }} () // file name fileName: = fileHeader. filenameif fileName = "" {log. fatal ("Param filename cannot be null. ") return} // file content bytes, err: = ioutil. readAll (file) // write to the local file outputFilePath: = "/home/admin/desktop/" + fileNameerr = ioutil. writeFile (outputFilePath, bytes, OS. modePerm) if err! = Nil {log. Fatal ("WriteFileError:", err. Error () return} w. Write ([] byte) ("File Uploaded successfully! "))}