Set up a Web Server with Go and upload files from the Android application
PC Windows10 Android Studio 4.0 Kotlin 1.3.72 Android device Emulator (API Level 29) Go 1.11.1
Send a file from the Android app, save it on the server side, and return the status code from the server to the app
Server.go
package controllers
import (
"fmt"
"net/http"
"io/ioutil"
"os"
)
func apiSampleHandler(w http.ResponseWriter, r *http.Request) {
switch(r.Method) {
case "POST":
fmt.Println("POST")
//Get uploaded files and headers
file, fileHeader, _ := r.FormFile ("upload_file")
fileName := fileHeader.Filename //Get the filename from the header
defer file.Close() //Close the file at the end
data, _ := ioutil.ReadAll(file) //Read file
saveFile, _ := os.Create(fileName) //Generate a file for saving
defer saveFile.Close() //Close the file for saving at the end
_, err = saveFile.Write(data) //Write to file
if err != nil {
fmt.Println("can not write file")
w.WriteHeader(http.StatusBadRequest)
return
}
case "GET":
fmt.Println("GET")
}
// 200:Returns OK
w.WriteHeader(http.StatusOK)
}
// main.Call from go to start the server
func StartWebServer() error {
http.HandleFunc("/", apiSampleHandler)
return http.ListenAndServe(":8080", nil)
}
Run main.go and start the server Go to http: // localhost: 8080 and make sure the server is up
Define Permission to access the Internet
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Since the http communication setting is turned off from Android 9.0, set uses CleartextTrafic
to true
AndroidManifest.xml
<application
abridgement
android:usesCleartextTraffic="true">
<activity android:name=".MainActivity">
abridgement
</activity>
</application>
Generate a text file in the application-specific area of the Android device (under `` `/ data / data / {package_name} / files```)
File.kt
const val FILE_EXPAND = ".txt"
class File {
fun makeTxtFile(context: Context, fileName: String, str: String) {
try {
context.openFileOutput(fileName + FILE_EXPAND, Context.MODE_PRIVATE).use {
it.write(str.toByteArray())
}
} catch (e: IOException) {
Log.e("File", "#makeTxtFile $e")
}
}
}
Confirm file generation View files on the device with Device File Explorer (https://developer.android.com/studio/debug/device-file-explorer?hl=ja )
Read the file and send the file via http communication
Net.kt
fun startConnection(context: Context, requestUrl: String, requestMethod: String, fileName: String): Pair<Int, String> {
val url = URL(requestUrl) //URL object generation
//UrlConnection object creation
val urlConnection = url.openConnection() as HttpURLConnection
var result = ""
var responseCode = 0
try {
val boundary = "--------------------------"
urlConnection.requestMethod = requestMethod // POST,GET etc.
urlConnection.doOutput = true //Send request body
urlConnection.doInput = true //Reception of response body
urlConnection.useCaches = false //Use of cache
// multipart/form-data: Send multiple data, boundary: Separation between multiple data
urlConnection.setRequestProperty(
"Content-Type",
"multipart/form-data; boundary=$boundary"
)
val filePath = context.filesDir //App-specific area path
val file = File("$filePath/$fileName$FILE_EXPAND") //Create a file object
FileInputStream(file).use { fileInputStream ->
urlConnection.connect() //Establish a connection
DataOutputStream(urlConnection.outputStream).use {
it.writeBytes( //Set header
TWO_HYPHEN + boundary + LINE_END +
"Content-Disposition: form-data; name=\"upload_file\"; " +
"filename=\"$fileName$FILE_EXPAND\"$LINE_END" +
"Content-Type: application/octet-stream$LINE_END$LINE_END"
)
//File writing
val buffer = ByteArray(BUFFER_SIZE)
var bytesRead: Int
do {
bytesRead = fileInputStream.read(buffer)
if (bytesRead == -1) break
it.write(buffer, 0, bytesRead)
} while (true)
it.writeBytes( //footer settings
LINE_END + TWO_HYPHEN + boundary + TWO_HYPHEN + LINE_END
)
it.flush()
}
}
responseCode = urlConnection.responseCode //Get response code
BufferedReader(InputStreamReader(urlConnection.inputStream)).use {
val sb = StringBuffer()
for (line in it.readLines()) {
line.let { sb.append(line) }
}
result = sb.toString()
}
} catch (e: Exception) {
Log.e("Net", "#startConnection$e")
} finally {
urlConnection.disconnect()
}
return responseCode to result
}
}
Confirm the IP address of the server (PC) you want to access by executing the following with the command prompt
>ipconfig
Set http: // {confirmed IP address}: 8080 in requestUrl of Net # startConnection and execute the application
Check the same directory as main.go on your PC Complete if the file has been created
The whole source is here The access destination, RequestMethod, and file name can be changed dynamically by the application.
[Android] Save files in the app FileOutputStream, FileInputStream Upload File To Server - Android Example [Android] while-FileInputStream.read error in kotlin [Kotlin] I want to return multiple values!
Recommended Posts